hostinger-api-mcp 4.5.1 → 4.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/gemini-extension.json +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
- package/skills/headless/VERSION +2 -2
- package/skills/headless/steps/03-provision/pocketbase/SKILL.md +4 -1
- package/skills/headless/steps/04-content-model/pocketbase/frontend.md +1 -1
- package/skills/headless/steps/04-content-model/pocketbase/scripts/pb-apply-schema.mjs +8 -0
- package/skills/headless/steps/04-content-model/pocketbase/scripts/pb-lib.mjs +6 -1
- package/skills/headless/steps/04-content-model/pocketbase/scripts/pb-verify.mjs +12 -0
- package/skills/headless/steps/06-frontend/SKILL.md +2 -1
- package/src/core/skills.js +18 -18
- package/src/core/skills.ts +18 -18
- package/src/servers/agency-hosting.js +1 -1
- package/src/servers/agency-hosting.ts +1 -1
- package/src/servers/agent-readiness.js +1 -1
- package/src/servers/agent-readiness.ts +1 -1
- package/src/servers/all.js +1 -1
- package/src/servers/all.ts +1 -1
- package/src/servers/billing.js +1 -1
- package/src/servers/billing.ts +1 -1
- package/src/servers/dns.js +1 -1
- package/src/servers/dns.ts +1 -1
- package/src/servers/domains.js +1 -1
- package/src/servers/domains.ts +1 -1
- package/src/servers/ecommerce.js +1 -1
- package/src/servers/ecommerce.ts +1 -1
- package/src/servers/gpu.js +1 -1
- package/src/servers/gpu.ts +1 -1
- package/src/servers/horizons.js +1 -1
- package/src/servers/horizons.ts +1 -1
- package/src/servers/hosting.js +1 -1
- package/src/servers/hosting.ts +1 -1
- package/src/servers/mail.js +1 -1
- package/src/servers/mail.ts +1 -1
- package/src/servers/reach.js +1 -1
- package/src/servers/reach.ts +1 -1
- package/src/servers/vps.js +1 -1
- package/src/servers/vps.ts +1 -1
- package/src/servers/wordpress.js +1 -1
- package/src/servers/wordpress.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,13 @@ Generated at release time from the diff between the previous and current
|
|
|
4
4
|
build. Tool changes are listed individually; everything else is summarised
|
|
5
5
|
by area.
|
|
6
6
|
|
|
7
|
+
## v4.5.2 — 2026-11-17
|
|
8
|
+
|
|
9
|
+
### Also in this release
|
|
10
|
+
|
|
11
|
+
- Bundled agent skills: 7 files
|
|
12
|
+
- Other files: `src/core/skills.js`, `src/core/skills.ts`
|
|
13
|
+
|
|
7
14
|
## v4.5.1 — 2026-11-17
|
|
8
15
|
|
|
9
16
|
### Also in this release
|
package/gemini-extension.json
CHANGED
package/package.json
CHANGED
package/server.json
CHANGED
|
@@ -17,12 +17,12 @@
|
|
|
17
17
|
"url": "https://github.com/hostinger/api-mcp-server",
|
|
18
18
|
"source": "github"
|
|
19
19
|
},
|
|
20
|
-
"version": "4.5.
|
|
20
|
+
"version": "4.5.2",
|
|
21
21
|
"packages": [
|
|
22
22
|
{
|
|
23
23
|
"registryType": "npm",
|
|
24
24
|
"identifier": "@hostinger/mcp",
|
|
25
|
-
"version": "4.5.
|
|
25
|
+
"version": "4.5.2",
|
|
26
26
|
"transport": {
|
|
27
27
|
"type": "stdio"
|
|
28
28
|
},
|
package/skills/headless/VERSION
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
version=4.5.
|
|
2
|
-
commit=
|
|
1
|
+
version=4.5.2
|
|
2
|
+
commit=53f8601d8cc1
|
|
3
3
|
built=2026-11-17
|
|
@@ -98,7 +98,10 @@ it runs at the join.
|
|
|
98
98
|
with `hosting_pocketbase_set-superuser { username, domain }` (no password, so a strong one is
|
|
99
99
|
generated) and save the response as in point 2; when it may belong to something else, **ask** first.
|
|
100
100
|
2. **Create it.** `hosting_pocketbase_create-backend { username, domain }` **without**
|
|
101
|
-
`superuser_password`.
|
|
101
|
+
`superuser_password`. Before the call, make the folder private:
|
|
102
|
+
`mkdir -p ~/.hostinger/<domain>/.pocketbase && chmod 700 ~/.hostinger/<domain>/.pocketbase`, so
|
|
103
|
+
other users of this computer can't read the file even before its own `chmod`. As soon as the call
|
|
104
|
+
returns, before any other step or message, write the
|
|
102
105
|
**full response** to `~/.hostinger/<domain>/.pocketbase/credentials.json` with your file-writing
|
|
103
106
|
tool and `chmod 600` it (on Windows the profile folder is already private). It holds `domain`,
|
|
104
107
|
`api_url`, `admin_url`, `superuser_email`, `superuser_password`, `instance_id`, `state` and
|
|
@@ -111,7 +111,7 @@ const unsubscribe = await pb.collection("messages").subscribe(
|
|
|
111
111
|
A Node.js app on the site can call its own backend at `https://<domain>` for trusted server-side work (webhooks, scheduled jobs, writes visitors must not make):
|
|
112
112
|
|
|
113
113
|
1. Store `PB_URL`, `PB_SUPERUSER_EMAIL` and `PB_SUPERUSER_PASSWORD` as Node.js environment variables. `hosting_nodejs_replace-environment-variables` replaces the full set, so read the current ones first and send them all.
|
|
114
|
-
2.
|
|
114
|
+
2. Do superuser work on its own client in a server-only module (e.g. `src/lib/pb-admin.ts`), used only by that trusted work: authenticate it once at startup with `admin.collection("_superusers").authWithPassword(email, password)` and again on a 401. Never sign in the shared `pb` client: pages rendered and requests handled for visitors would then run as superuser and skip every collection rule. Server code acting for a visitor uses a client with no superuser sign-in (a new `PocketBase` per request when it carries the visitor's own sign-in).
|
|
115
115
|
3. The app's own routes must not start with `/api` or `/_`; those paths go to PocketBase.
|
|
116
116
|
4. For realtime subscriptions from Node.js, check the HTTP/1.1 note in `troubleshooting.md`.
|
|
117
117
|
|
|
@@ -178,6 +178,14 @@ async function updateFieldsAndIndexes(group) {
|
|
|
178
178
|
const desired = withTimestamps(collection, (collection.fields ?? []).map(toApiField), existing.fields)
|
|
179
179
|
body.fields = mergeFields(existing, desired)
|
|
180
180
|
body.indexes = mergeIndexes(existing.indexes, collection.indexes)
|
|
181
|
+
// A new field is writable under the old rules until applyRules() runs (it goes last because rules
|
|
182
|
+
// may name fields of collections synced later), so lock the writes it will replace meanwhile. An
|
|
183
|
+
// aborted run then leaves them superuser-only, not open.
|
|
184
|
+
if (desired.some((field) => !existing.fields.some((f) => f.name === field.name))) {
|
|
185
|
+
for (const key of ["create", "update"]) {
|
|
186
|
+
if (key in (collection.rules ?? {})) body[RULE_KEYS[key]] = null
|
|
187
|
+
}
|
|
188
|
+
}
|
|
181
189
|
}
|
|
182
190
|
if (collection.authOptions) Object.assign(body, collection.authOptions)
|
|
183
191
|
if (!Object.keys(body).length) continue
|
|
@@ -19,7 +19,12 @@ export function readCredentials(path) {
|
|
|
19
19
|
const mode = fs.statSync(path).mode
|
|
20
20
|
const readableByOthers = (mode & 0o077) !== 0
|
|
21
21
|
if (readableByOthers && process.platform !== "win32") {
|
|
22
|
-
|
|
22
|
+
try {
|
|
23
|
+
fs.chmodSync(path, 0o600)
|
|
24
|
+
console.warn(`WARN ${path} was readable by other users; it is now mode 600. If this computer is shared, rotate the password with hosting_pocketbase_set-superuser.`)
|
|
25
|
+
} catch {
|
|
26
|
+
console.warn(`WARN ${path} is readable by other users; run: chmod 600 ${path}`)
|
|
27
|
+
}
|
|
23
28
|
}
|
|
24
29
|
return creds
|
|
25
30
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process"
|
|
2
|
+
import { homedir } from "node:os"
|
|
3
|
+
import path from "node:path"
|
|
2
4
|
import { baseUrlFrom, listCollections, readCredentials, readJson, request, superuserToken } from "./pb-lib.mjs"
|
|
3
5
|
|
|
4
6
|
const REALTIME_PROBE_SECONDS = "8"
|
|
@@ -86,9 +88,19 @@ if (settings.data?.smtp && !settings.data.smtp.enabled) {
|
|
|
86
88
|
console.log("INFO outgoing mail (SMTP) is off: verification and password-reset emails are not sent")
|
|
87
89
|
}
|
|
88
90
|
|
|
91
|
+
// curl is found by name, and Windows looks in the working directory (the user's project, maybe a
|
|
92
|
+
// cloned repository) before PATH, as does a relative PATH entry elsewhere: run it from the home folder
|
|
93
|
+
// with only absolute PATH entries, as connect/launch.mjs does for npx.
|
|
94
|
+
const curlEnv = { ...process.env }
|
|
95
|
+
for (const key of Object.keys(curlEnv).filter((k) => k.toUpperCase() === "PATH")) {
|
|
96
|
+
curlEnv[key] = curlEnv[key].split(path.delimiter).filter((p) => path.isAbsolute(p)).join(path.delimiter)
|
|
97
|
+
}
|
|
98
|
+
|
|
89
99
|
function probeRealtime(protocol) {
|
|
90
100
|
try {
|
|
91
101
|
const out = execFileSync("curl", ["-sS", "-N", protocol, "--max-time", REALTIME_PROBE_SECONDS, "-H", "Accept: text/event-stream", `${base}/api/realtime`], {
|
|
102
|
+
cwd: homedir(),
|
|
103
|
+
env: curlEnv,
|
|
92
104
|
encoding: "utf8",
|
|
93
105
|
stdio: ["ignore", "pipe", "ignore"],
|
|
94
106
|
})
|
|
@@ -116,7 +116,8 @@ Read the backend from `site.json`:
|
|
|
116
116
|
([`../04-content-model/pocketbase/auth.md`](../04-content-model/pocketbase/auth.md)). A public form
|
|
117
117
|
includes its recipe's honeypot field, empty and hidden. **The superuser password never reaches the
|
|
118
118
|
frontend**; server-side superuser work reads `PB_URL`, `PB_SUPERUSER_EMAIL` and
|
|
119
|
-
`PB_SUPERUSER_PASSWORD` from the app's environment variables
|
|
119
|
+
`PB_SUPERUSER_PASSWORD` from the app's environment variables and signs in **its own** server-only
|
|
120
|
+
client, never the shared `pb` that renders pages for visitors (`frontend.md`, Node.js apps). For an
|
|
120
121
|
existing app, keep its screens and swap its data calls to the backend.
|
|
121
122
|
|
|
122
123
|
Guidelines (framework-agnostic):
|
package/src/core/skills.js
CHANGED
|
@@ -190,10 +190,10 @@ export default [
|
|
|
190
190
|
},
|
|
191
191
|
{
|
|
192
192
|
"uri": "skill://hostinger-headless/steps/03-provision/pocketbase/SKILL.md",
|
|
193
|
-
"digest": "sha256:
|
|
194
|
-
"size":
|
|
193
|
+
"digest": "sha256:a6c10a6378a365aef891ad00701efc731f94a4e7e7fa4647e5776561f91d280c",
|
|
194
|
+
"size": 12783,
|
|
195
195
|
"mimeType": "text/markdown",
|
|
196
|
-
"text": "---\nname: headless-step-provision-pocketbase\ndescription: \"Provision the PocketBase backend for the Hostinger Headless flow: create a headless website (type headless_pocketbase) or adopt the one onboarding made, then create its PocketBase backend with hosting_pocketbase_create-backend (database, visitor sign-in, file storage and realtime at /api, the owner's dashboard at /_/), save the one-time superuser password outside the deployable source, verify it answers, and record it in site.json. For any app, SPA or site whose visitors create its data.\"\n---\n\n# headless-step-provision-pocketbase\n\nProvision a **headless website with a PocketBase backend** for `<domain>` and prove it is ready. This\nis the backend for **any app, SPA or site whose visitors create the data it keeps** — accounts,\nbookings, comments, votes, scores, order requests, uploads, live messages. There is no CMS and no store\nengine here. PocketBase runs on the site's own domain: the REST and realtime API at\n`https://<domain>/api`, the owner's dashboard at `https://<domain>/_/`. Every other path is the\nfrontend that the frontend step builds and the deploy step ships as a Node.js application.\n**Out:** `site.json` and `~/.hostinger/<domain>/.pocketbase/credentials.json`.\n\n> **Not WordPress, not Ecommerce.** Never provision `headless_wordpress` / `headless_ecommerce` for a\n> PocketBase build, and never install WordPress at `/cms`: Hostinger refuses a PocketBase backend on a\n> headless WordPress site. The app owns every route except `/api` and `/_`.\n\nAll website operations below go through the Hostinger connector (`execute`). Read each operation's\n`inputSchema` (from `search`) before its first call.\n\n> **Fire vs join (background provision).** For a **fresh site**, the fire half is Step 2's\n> `hosting_websites_create`; the join half is `wait.mjs setup`, then Step 3 (the backend), Step 4 and\n> Step 5. For an **adopted shell** (onboarding's `headless_empty` or `headless_pocketbase` site), the\n> fire half is Step 3's `hosting_pocketbase_create-backend` call plus saving its response — one call\n> that returns at once — and the join half is `wait.mjs pocketbase`, Step 4 and Step 5. Record\n> `provision.in_progress` after the fire and return to the prepare work (see the router `../SKILL.md`);\n> join when an instance-barrier step needs the backend, or immediately if the agent can't interleave.\n> A site whose backend Step 1 already finds means provision is done: record `provision.completed` and\n> adopt it.\n\n## Step 0 — Preflight\n\n`search` with the query `pocketbase`. You need `hosting_pocketbase_create-backend`,\n`hosting_pocketbase_backend` and `hosting_pocketbase_set-superuser`; read each one's `inputSchema`\nbefore its first call. If any is missing, the connector is outdated: update it (connect's Phase 1\ninstall), log an `issue` event and stop. **Never improvise a database in its place.**\n\n## Step 1 — Detect before you create (never provision twice)\n\nRun these in order: the kind checks (points 1–3) decide whether this site may be used at all, before\nits setup status (point 4) says where to pick it up.\n\n1. `hosting_websites_list { \"domain\": \"<domain>\" }` — substring filter, so **exact-match** the row's\n `domain`. If a row exists, note `username`, `order_id`, `website_type`. No exact row → nothing\n exists on this domain → **create fresh** (Step 2).\n2. **A row of another kind** (`website_type` not `headless`: a WordPress or store site) → stop and\n tell the user — this domain already hosts something else. **Never create a second site.**\n3. **A `headless` row.** `wordpress_installations_list { username, domain, ownership: \"all\" }` with a\n `directory: \"cms\"` row → stop and tell the user: this is a headless WordPress site, and Hostinger\n refuses PocketBase there. Otherwise `hosting_pocketbase_backend { username, domain }`:\n - a backend (any `state` but `missing`) → **adopt it**; Step 3 point 1 settles the credentials\n (rotate the superuser when this build made the backend and the file is gone, otherwise ask).\n - 404, or `state: \"missing\"` → the shell is empty (onboarding's `headless_empty`, or a\n `headless_pocketbase` site whose backend wasn't created yet): **adopt the site, don't call\n `hosting_websites_create`**, and create the backend on it in Step 3 with this row's `username`.\n **Only provision PocketBase for a `pocketbase` brief.** A `wordpress` or `ecommerce` brief belongs\n in those subfolders — never give it a PocketBase backend.\n4. **Where to pick it up.** `hosting_websites_list-setups { \"domain\": \"<domain>\" }` — exact-match the row:\n - `completed`, or no row (it drops off after 24 h) → the website is ready → Step 3.\n - `running` → the setup is still going: at the join, `cd \"$HOME\" && node <skill>/wait.mjs setup <domain>`\n before Step 3.\n - `failed` → tell the user and point them at hPanel; do **not** call `hosting_websites_create` again on your own.\n\n## Step 2 — Create (only when nothing exists)\n\n1. Pick the plan: `hosting_orders_list { \"statuses\": [\"active\"] }`. One active order → use it; several\n → ask the user which.\n2. Start the setup as a **headless website marked for PocketBase** (it installs nothing yet; Step 3\n creates the backend):\n\n ```json\n { \"operation\": \"hosting_websites_create\",\n \"params\": { \"order_id\": <order_id>, \"type\": \"headless_pocketbase\", \"domain\": \"<domain>\" } }\n ```\n\n `domain` must be a **customer-owned** domain. For a temporary `*.hostingersite.com` subdomain,\n **omit `domain`** — the setup generates one itself and returns it in the response. Don't call a\n separate subdomain op to make one first: there's no need in this flow. The response then carries the\n generated domain: if it differs from the workspace directory name, move `~/.hostinger/<old>/` to\n `~/.hostinger/<new>/`\n (if `<new>/` already exists, stop and ask instead of moving into it),\n update the domain in `brief.md`, and tell the user the new domain.\n3. Don't wait here. At the join, `cd \"$HOME\" && node <skill>/wait.mjs setup <domain>` (see *Waiting on Hostinger* in\n the top-level `SKILL.md`) returns once the setup is `completed`, usually at once by then. A `failed`\n setup → stop, point at hPanel. Then Step 3.\n\n## Step 3 — Create the backend\n\nNeeds the website (setup `completed`). On an adopted shell this is the **fire** half; on a fresh site\nit runs at the join.\n\n1. **Already there?** `hosting_pocketbase_backend { username, domain }`. A backend plus\n `~/.hostinger/<domain>/.pocketbase/credentials.json` with a matching `domain` → adopt it and go to\n point 4. A backend without that file → the password is gone (Hostinger returns it once and never\n stores it): when this build made it (a resumed run, `site.json → backend: \"pocketbase\"`), rotate it\n with `hosting_pocketbase_set-superuser { username, domain }` (no password, so a strong one is\n generated) and save the response as in point 2; when it may belong to something else, **ask** first.\n2. **Create it.** `hosting_pocketbase_create-backend { username, domain }` **without**\n `superuser_password`. As soon as the call returns, before any other step or message, write the\n **full response** to `~/.hostinger/<domain>/.pocketbase/credentials.json` with your file-writing\n tool and `chmod 600` it (on Windows the profile folder is already private). It holds `domain`,\n `api_url`, `admin_url`, `superuser_email`, `superuser_password`, `instance_id`, `state` and\n `version`; **the password is returned only this once**. The file sits in the workspace, outside\n `src/`, so no deploy archive can include it. Never print the password or put it in `site.json`,\n `brief.md`, the run log or a chat reply.\n3. **A 422 is not always \"already exists\"**: read its message and show it to the user when you stop.\n - *This website already has a PocketBase instance* → go back to point 1 (once; if it still finds no\n backend, stop and show the user the message).\n - *not supported on headless WordPress websites* or *cannot be added to a parked domain* → stop\n and tell the user: this domain can't take PocketBase.\n - *not available* / *no access yet* (PocketBase is rolling out gradually and this account isn't\n enabled yet) → stop and tell the user PocketBase isn't enabled on their account yet, quoting the\n message; log an `issue` event. **Never improvise a database in its place.**\n - Any other message → stop and show it to the user. Never retry a 422 blindly.\n4. **Wait for it.** `state` may be `null` right after creation; that's normal.\n `cd \"$HOME\" && node <skill>/wait.mjs pocketbase <domain>` returns once `https://<domain>/api/health`\n answers 200 (over `http://` with `https_pending: true` while a new domain's certificate is still\n installing — fine, go on). If it times out, re-read `hosting_pocketbase_backend`: `failed` means\n the last start didn't succeed and Hostinger retries it on its own after `retry_after_seconds`\n (the data is intact — wait that long and read again, never delete the backend); `unregistered`\n means it's broken → stop and show the user; `missing` means its files are gone → point 2 creates\n a new, empty one. The backend sleeps after about 5 idle minutes, so one 503 on a first request is\n a wake-up.\n\nPocketBase owns `/api` and `/_` on this domain; the app's own server routes use another prefix (e.g.\n`/server`). The owner sets outgoing mail (SMTP), backups and social sign-in in the dashboard: they\naren't in the API. `hosting_pocketbase_delete-backend` destroys every record and upload — never call\nit in this flow.\n\n## Step 4 — Verify\n\n| Check | How | Expect |\n|---|---|---|\n| Website exists | `hosting_websites_list` exact row | the row is present, `username` known |\n| Setup finished *(fresh site only)* | `hosting_websites_list-setups` exact row | `status: completed` |\n| Backend healthy | `hosting_pocketbase_backend { username, domain }` | `state` is `asleep`, `starting` or `running` |\n| PocketBase answers | `GET https://<domain>/api/health` and `GET https://<domain>/_/` | 200 and 200 |\n| Credentials saved | `~/.hostinger/<domain>/.pocketbase/credentials.json` | present, mode `600`, `domain` matches |\n\n`GET https://<domain>/` returns the Hostinger default page (or 403) until the frontend is deployed —\nexpected, not a failure. There is **no `/cms`** on this domain; the app itself serves every route but\n`/api` and `/_` once it is deployed (Step 8).\n\nIf a check fails: retry once after ~30 s; if it still fails, stop and point the user at hPanel.\n\n## Step 5 — Record `site.json`\n\n```json\n{\n \"backend\": \"pocketbase\",\n \"website_type\": \"headless\",\n \"order_id\": 1007223428,\n \"username\": \"u…\",\n \"runtime\": \"nodejs\",\n \"pocketbase\": {\n \"instance_id\": \"…\",\n \"version\": \"…\",\n \"superuser_email\": \"…\",\n \"credentials_file\": \".pocketbase/credentials.json\"\n },\n \"urls\": {\n \"site\": \"https://<domain>\",\n \"api\": \"https://<domain>/api\",\n \"admin\": \"https://<domain>/_/\"\n },\n \"provisioned_at\": \"…\",\n \"verified_at\": \"…\"\n}\n```\n\n`credentials_file` is relative to the workspace `~/.hostinger/<domain>/`. No passwords or tokens in\n`site.json` — the superuser password lives only in the credentials file. Together, `superuser_email`\nand that file are the owner's **login access** to the dashboard at `urls.admin`; the done step hands\nthem over by name (the email, the file's full path, never the password itself).\n\n## Content model & deploy (what happens next)\n\n- **Content model** runs `../../04-content-model/pocketbase/SKILL.md`: it designs the collections,\n access rules and seed records in `pocketbase/schema.json` during the provision wait, then applies\n and verifies them against this backend at the instance barrier. The shared prepare phase still\n writes the site's fixed copy (title, navigation, pages) to `content-model.md`.\n- **Deploy** is a standard Node.js application deploy, handled by `../../08-deploy/SKILL.md`: it archives\n the **source** (not the build output; exclude `node_modules/`, `.next/`, `dist/`, build output and\n `.git/`), then deploys with `hosting_deploy` (`type: \"nodejs\"`, upload + server-side `npm install` +\n build, one shot) passing the framework's `appType` + `outputDirectory` inline, and polls\n `hosting_get-deployment` until the build completes. Any supported `appType` works (Next.js, Nuxt,\n Express, NestJS, Fastify, Vite/React/Vue SPA, …). `/api` and `/_` keep belonging to PocketBase; deploy\n checks they survived.\n"
|
|
196
|
+
"text": "---\nname: headless-step-provision-pocketbase\ndescription: \"Provision the PocketBase backend for the Hostinger Headless flow: create a headless website (type headless_pocketbase) or adopt the one onboarding made, then create its PocketBase backend with hosting_pocketbase_create-backend (database, visitor sign-in, file storage and realtime at /api, the owner's dashboard at /_/), save the one-time superuser password outside the deployable source, verify it answers, and record it in site.json. For any app, SPA or site whose visitors create its data.\"\n---\n\n# headless-step-provision-pocketbase\n\nProvision a **headless website with a PocketBase backend** for `<domain>` and prove it is ready. This\nis the backend for **any app, SPA or site whose visitors create the data it keeps** — accounts,\nbookings, comments, votes, scores, order requests, uploads, live messages. There is no CMS and no store\nengine here. PocketBase runs on the site's own domain: the REST and realtime API at\n`https://<domain>/api`, the owner's dashboard at `https://<domain>/_/`. Every other path is the\nfrontend that the frontend step builds and the deploy step ships as a Node.js application.\n**Out:** `site.json` and `~/.hostinger/<domain>/.pocketbase/credentials.json`.\n\n> **Not WordPress, not Ecommerce.** Never provision `headless_wordpress` / `headless_ecommerce` for a\n> PocketBase build, and never install WordPress at `/cms`: Hostinger refuses a PocketBase backend on a\n> headless WordPress site. The app owns every route except `/api` and `/_`.\n\nAll website operations below go through the Hostinger connector (`execute`). Read each operation's\n`inputSchema` (from `search`) before its first call.\n\n> **Fire vs join (background provision).** For a **fresh site**, the fire half is Step 2's\n> `hosting_websites_create`; the join half is `wait.mjs setup`, then Step 3 (the backend), Step 4 and\n> Step 5. For an **adopted shell** (onboarding's `headless_empty` or `headless_pocketbase` site), the\n> fire half is Step 3's `hosting_pocketbase_create-backend` call plus saving its response — one call\n> that returns at once — and the join half is `wait.mjs pocketbase`, Step 4 and Step 5. Record\n> `provision.in_progress` after the fire and return to the prepare work (see the router `../SKILL.md`);\n> join when an instance-barrier step needs the backend, or immediately if the agent can't interleave.\n> A site whose backend Step 1 already finds means provision is done: record `provision.completed` and\n> adopt it.\n\n## Step 0 — Preflight\n\n`search` with the query `pocketbase`. You need `hosting_pocketbase_create-backend`,\n`hosting_pocketbase_backend` and `hosting_pocketbase_set-superuser`; read each one's `inputSchema`\nbefore its first call. If any is missing, the connector is outdated: update it (connect's Phase 1\ninstall), log an `issue` event and stop. **Never improvise a database in its place.**\n\n## Step 1 — Detect before you create (never provision twice)\n\nRun these in order: the kind checks (points 1–3) decide whether this site may be used at all, before\nits setup status (point 4) says where to pick it up.\n\n1. `hosting_websites_list { \"domain\": \"<domain>\" }` — substring filter, so **exact-match** the row's\n `domain`. If a row exists, note `username`, `order_id`, `website_type`. No exact row → nothing\n exists on this domain → **create fresh** (Step 2).\n2. **A row of another kind** (`website_type` not `headless`: a WordPress or store site) → stop and\n tell the user — this domain already hosts something else. **Never create a second site.**\n3. **A `headless` row.** `wordpress_installations_list { username, domain, ownership: \"all\" }` with a\n `directory: \"cms\"` row → stop and tell the user: this is a headless WordPress site, and Hostinger\n refuses PocketBase there. Otherwise `hosting_pocketbase_backend { username, domain }`:\n - a backend (any `state` but `missing`) → **adopt it**; Step 3 point 1 settles the credentials\n (rotate the superuser when this build made the backend and the file is gone, otherwise ask).\n - 404, or `state: \"missing\"` → the shell is empty (onboarding's `headless_empty`, or a\n `headless_pocketbase` site whose backend wasn't created yet): **adopt the site, don't call\n `hosting_websites_create`**, and create the backend on it in Step 3 with this row's `username`.\n **Only provision PocketBase for a `pocketbase` brief.** A `wordpress` or `ecommerce` brief belongs\n in those subfolders — never give it a PocketBase backend.\n4. **Where to pick it up.** `hosting_websites_list-setups { \"domain\": \"<domain>\" }` — exact-match the row:\n - `completed`, or no row (it drops off after 24 h) → the website is ready → Step 3.\n - `running` → the setup is still going: at the join, `cd \"$HOME\" && node <skill>/wait.mjs setup <domain>`\n before Step 3.\n - `failed` → tell the user and point them at hPanel; do **not** call `hosting_websites_create` again on your own.\n\n## Step 2 — Create (only when nothing exists)\n\n1. Pick the plan: `hosting_orders_list { \"statuses\": [\"active\"] }`. One active order → use it; several\n → ask the user which.\n2. Start the setup as a **headless website marked for PocketBase** (it installs nothing yet; Step 3\n creates the backend):\n\n ```json\n { \"operation\": \"hosting_websites_create\",\n \"params\": { \"order_id\": <order_id>, \"type\": \"headless_pocketbase\", \"domain\": \"<domain>\" } }\n ```\n\n `domain` must be a **customer-owned** domain. For a temporary `*.hostingersite.com` subdomain,\n **omit `domain`** — the setup generates one itself and returns it in the response. Don't call a\n separate subdomain op to make one first: there's no need in this flow. The response then carries the\n generated domain: if it differs from the workspace directory name, move `~/.hostinger/<old>/` to\n `~/.hostinger/<new>/`\n (if `<new>/` already exists, stop and ask instead of moving into it),\n update the domain in `brief.md`, and tell the user the new domain.\n3. Don't wait here. At the join, `cd \"$HOME\" && node <skill>/wait.mjs setup <domain>` (see *Waiting on Hostinger* in\n the top-level `SKILL.md`) returns once the setup is `completed`, usually at once by then. A `failed`\n setup → stop, point at hPanel. Then Step 3.\n\n## Step 3 — Create the backend\n\nNeeds the website (setup `completed`). On an adopted shell this is the **fire** half; on a fresh site\nit runs at the join.\n\n1. **Already there?** `hosting_pocketbase_backend { username, domain }`. A backend plus\n `~/.hostinger/<domain>/.pocketbase/credentials.json` with a matching `domain` → adopt it and go to\n point 4. A backend without that file → the password is gone (Hostinger returns it once and never\n stores it): when this build made it (a resumed run, `site.json → backend: \"pocketbase\"`), rotate it\n with `hosting_pocketbase_set-superuser { username, domain }` (no password, so a strong one is\n generated) and save the response as in point 2; when it may belong to something else, **ask** first.\n2. **Create it.** `hosting_pocketbase_create-backend { username, domain }` **without**\n `superuser_password`. Before the call, make the folder private:\n `mkdir -p ~/.hostinger/<domain>/.pocketbase && chmod 700 ~/.hostinger/<domain>/.pocketbase`, so\n other users of this computer can't read the file even before its own `chmod`. As soon as the call\n returns, before any other step or message, write the\n **full response** to `~/.hostinger/<domain>/.pocketbase/credentials.json` with your file-writing\n tool and `chmod 600` it (on Windows the profile folder is already private). It holds `domain`,\n `api_url`, `admin_url`, `superuser_email`, `superuser_password`, `instance_id`, `state` and\n `version`; **the password is returned only this once**. The file sits in the workspace, outside\n `src/`, so no deploy archive can include it. Never print the password or put it in `site.json`,\n `brief.md`, the run log or a chat reply.\n3. **A 422 is not always \"already exists\"**: read its message and show it to the user when you stop.\n - *This website already has a PocketBase instance* → go back to point 1 (once; if it still finds no\n backend, stop and show the user the message).\n - *not supported on headless WordPress websites* or *cannot be added to a parked domain* → stop\n and tell the user: this domain can't take PocketBase.\n - *not available* / *no access yet* (PocketBase is rolling out gradually and this account isn't\n enabled yet) → stop and tell the user PocketBase isn't enabled on their account yet, quoting the\n message; log an `issue` event. **Never improvise a database in its place.**\n - Any other message → stop and show it to the user. Never retry a 422 blindly.\n4. **Wait for it.** `state` may be `null` right after creation; that's normal.\n `cd \"$HOME\" && node <skill>/wait.mjs pocketbase <domain>` returns once `https://<domain>/api/health`\n answers 200 (over `http://` with `https_pending: true` while a new domain's certificate is still\n installing — fine, go on). If it times out, re-read `hosting_pocketbase_backend`: `failed` means\n the last start didn't succeed and Hostinger retries it on its own after `retry_after_seconds`\n (the data is intact — wait that long and read again, never delete the backend); `unregistered`\n means it's broken → stop and show the user; `missing` means its files are gone → point 2 creates\n a new, empty one. The backend sleeps after about 5 idle minutes, so one 503 on a first request is\n a wake-up.\n\nPocketBase owns `/api` and `/_` on this domain; the app's own server routes use another prefix (e.g.\n`/server`). The owner sets outgoing mail (SMTP), backups and social sign-in in the dashboard: they\naren't in the API. `hosting_pocketbase_delete-backend` destroys every record and upload — never call\nit in this flow.\n\n## Step 4 — Verify\n\n| Check | How | Expect |\n|---|---|---|\n| Website exists | `hosting_websites_list` exact row | the row is present, `username` known |\n| Setup finished *(fresh site only)* | `hosting_websites_list-setups` exact row | `status: completed` |\n| Backend healthy | `hosting_pocketbase_backend { username, domain }` | `state` is `asleep`, `starting` or `running` |\n| PocketBase answers | `GET https://<domain>/api/health` and `GET https://<domain>/_/` | 200 and 200 |\n| Credentials saved | `~/.hostinger/<domain>/.pocketbase/credentials.json` | present, mode `600`, `domain` matches |\n\n`GET https://<domain>/` returns the Hostinger default page (or 403) until the frontend is deployed —\nexpected, not a failure. There is **no `/cms`** on this domain; the app itself serves every route but\n`/api` and `/_` once it is deployed (Step 8).\n\nIf a check fails: retry once after ~30 s; if it still fails, stop and point the user at hPanel.\n\n## Step 5 — Record `site.json`\n\n```json\n{\n \"backend\": \"pocketbase\",\n \"website_type\": \"headless\",\n \"order_id\": 1007223428,\n \"username\": \"u…\",\n \"runtime\": \"nodejs\",\n \"pocketbase\": {\n \"instance_id\": \"…\",\n \"version\": \"…\",\n \"superuser_email\": \"…\",\n \"credentials_file\": \".pocketbase/credentials.json\"\n },\n \"urls\": {\n \"site\": \"https://<domain>\",\n \"api\": \"https://<domain>/api\",\n \"admin\": \"https://<domain>/_/\"\n },\n \"provisioned_at\": \"…\",\n \"verified_at\": \"…\"\n}\n```\n\n`credentials_file` is relative to the workspace `~/.hostinger/<domain>/`. No passwords or tokens in\n`site.json` — the superuser password lives only in the credentials file. Together, `superuser_email`\nand that file are the owner's **login access** to the dashboard at `urls.admin`; the done step hands\nthem over by name (the email, the file's full path, never the password itself).\n\n## Content model & deploy (what happens next)\n\n- **Content model** runs `../../04-content-model/pocketbase/SKILL.md`: it designs the collections,\n access rules and seed records in `pocketbase/schema.json` during the provision wait, then applies\n and verifies them against this backend at the instance barrier. The shared prepare phase still\n writes the site's fixed copy (title, navigation, pages) to `content-model.md`.\n- **Deploy** is a standard Node.js application deploy, handled by `../../08-deploy/SKILL.md`: it archives\n the **source** (not the build output; exclude `node_modules/`, `.next/`, `dist/`, build output and\n `.git/`), then deploys with `hosting_deploy` (`type: \"nodejs\"`, upload + server-side `npm install` +\n build, one shot) passing the framework's `appType` + `outputDirectory` inline, and polls\n `hosting_get-deployment` until the build completes. Any supported `appType` works (Next.js, Nuxt,\n Express, NestJS, Fastify, Vite/React/Vue SPA, …). `/api` and `/_` keep belonging to PocketBase; deploy\n checks they survived.\n"
|
|
197
197
|
},
|
|
198
198
|
{
|
|
199
199
|
"uri": "skill://hostinger-headless/steps/03-provision/wordpress/SKILL.md",
|
|
@@ -239,10 +239,10 @@ export default [
|
|
|
239
239
|
},
|
|
240
240
|
{
|
|
241
241
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/frontend.md",
|
|
242
|
-
"digest": "sha256:
|
|
243
|
-
"size":
|
|
242
|
+
"digest": "sha256:d74e777e152651bd16642f2bef3d504f4cd8ddb3fcdf336eef655880d4627d10",
|
|
243
|
+
"size": 6385,
|
|
244
244
|
"mimeType": "text/markdown",
|
|
245
|
-
"text": "# Connecting the app\n\nThe backend is on the same domain as the site, so the browser needs no API URL, no CORS setup and no keys.\n\n## Contents\n\n- Bundled apps, plain HTML, local development\n- Everyday calls, pagination, errors\n- Files\n- Realtime\n- Node.js apps on the same website\n- Routing for single-page apps\n\n## Bundled apps (Vite, React, Vue, Svelte, Next.js static export)\n\n```bash\nnpm install pocketbase@0.28.1\n```\n\n```ts\nimport PocketBase from \"pocketbase\"\n\nexport const pb = new PocketBase(import.meta.env.DEV ? \"https://<domain>\" : window.location.origin)\npb.autoCancellation(false)\n```\n\n`autoCancellation(false)` matters: by default the SDK aborts an earlier request to the same collection when a new one starts, so parallel loads fail with \"The request was aborted\". For Next.js use `process.env.NODE_ENV === \"development\"` in place of `import.meta.env.DEV`.\n\n## Plain HTML\n\n```html\n<script src=\"https://cdn.jsdelivr.net/npm/pocketbase@0.28.1/dist/pocketbase.umd.js\"></script>\n<script>\n const pb = new PocketBase(window.location.origin)\n pb.autoCancellation(false)\n</script>\n```\n\n## Local development\n\nThere is one backend, the live one. In development the app talks to it directly (above), not through a dev-server proxy: a proxy works for REST but realtime through it depends on HTTP/1.1 (`troubleshooting.md`). Records created while testing are real data; delete them in the dashboard before handing over, or use a test account. Opening the app from `file://` does not work for same-origin calls; use the dev server.\n\n## Everyday calls\n\n```ts\nconst page = await pb.collection(\"posts\").getList(1, 20, {\n filter: pb.filter(\"published = {:p} && author = {:a}\", { p: true, a: userId }),\n sort: \"-created\",\n expand: \"author\",\n})\nconst all = await pb.collection(\"products\").getFullList({ sort: \"name\" })\nconst one = await pb.collection(\"posts\").getOne(id)\nconst first = await pb.collection(\"rooms\").getFirstListItem(pb.filter(\"slug = {:s}\", { s: slug }))\nconst post = await pb.collection(\"posts\").create({ title, author: pb.authStore.record.id })\nawait pb.collection(\"posts\").update(post.id, { published: true })\nawait pb.collection(\"posts\").delete(post.id)\n```\n\n- Build every filter with `pb.filter(expr, params)`; never put user input into a filter string yourself.\n- `getList` returns `{ items, page, perPage, totalItems, totalPages }`; `perPage` goes up to 1000. Show \"Load more\" with the next `page`, or pass `skipTotal: true` when the count is not needed (faster).\n- `getFullList` fetches every page; use it only for small collections such as a catalog.\n- `expand: \"author\"` puts the related record in `record.expand.author`, but only if the caller may view it under that collection's rules.\n\n## Errors\n\nErrors are `ClientResponseError` with `status` and `response`:\n\n- 400 with `response.data.<field>.message`: show that message next to the field.\n- 400 \"Failed to create record.\" with empty `data`: the create rule rejected it (honeypot filled, wrong owner, room closed). Show a general \"Could not send\" and check the rule.\n- 404 on view, update or delete: not found or not allowed by the rule.\n- 403: the rule is `null` (superusers only).\n- 429: rate limit. Ask the visitor to wait a minute.\n- `status` 0: network error or aborted request.\n\n## Files\n\n```ts\nconst form = new FormData()\nform.append(\"title\", title)\nform.append(\"cover\", fileInput.files[0])\nconst post = await pb.collection(\"posts\").create(form)\nconst url = pb.files.getURL(post, post.cover, { thumb: \"400x300\" })\n```\n\n- Files over the field's `maxSize` (default 5 MB) are rejected with a field error; check `file.size` before uploading.\n- Thumbnails work only for sizes listed in the field's `thumbs`.\n- For `protected` file fields, fetch a token first: `const token = await pb.files.getToken()` and pass `{ token }` to `getURL`. It expires after a few minutes.\n\n## Realtime\n\n```ts\nconst unsubscribe = await pb.collection(\"messages\").subscribe(\n \"*\",\n (event) => {\n if (event.action === \"create\") add(event.record)\n if (event.action === \"update\") replace(event.record)\n if (event.action === \"delete\") remove(event.record.id)\n },\n { filter: pb.filter(\"room = {:room}\", { room: roomId }), expand: \"author\" },\n)\n```\n\n- Load the initial list first, then subscribe, and merge by `id` so nothing shows twice.\n- Call `unsubscribe()` when the view unmounts.\n- `pb.realtime.isConnected` tells whether the stream is up; show a small \"Live\" or \"Connecting\" indicator.\n- Events follow the collection's view rule: a visitor only receives records they may view.\n- An idle backend sleeps after about 5 minutes and wakes on the next request; an open realtime stream keeps it awake. The first request after sleep can take a few seconds or return 503 once, so retry once and keep timeouts at 10 s or more.\n\n## Node.js apps on the same website\n\nA Node.js app on the site can call its own backend at `https://<domain>` for trusted server-side work (webhooks, scheduled jobs, writes visitors must not make):\n\n1. Store `PB_URL`, `PB_SUPERUSER_EMAIL` and `PB_SUPERUSER_PASSWORD` as Node.js environment variables. `hosting_nodejs_replace-environment-variables` replaces the full set, so read the current ones first and send them all.\n2.
|
|
245
|
+
"text": "# Connecting the app\n\nThe backend is on the same domain as the site, so the browser needs no API URL, no CORS setup and no keys.\n\n## Contents\n\n- Bundled apps, plain HTML, local development\n- Everyday calls, pagination, errors\n- Files\n- Realtime\n- Node.js apps on the same website\n- Routing for single-page apps\n\n## Bundled apps (Vite, React, Vue, Svelte, Next.js static export)\n\n```bash\nnpm install pocketbase@0.28.1\n```\n\n```ts\nimport PocketBase from \"pocketbase\"\n\nexport const pb = new PocketBase(import.meta.env.DEV ? \"https://<domain>\" : window.location.origin)\npb.autoCancellation(false)\n```\n\n`autoCancellation(false)` matters: by default the SDK aborts an earlier request to the same collection when a new one starts, so parallel loads fail with \"The request was aborted\". For Next.js use `process.env.NODE_ENV === \"development\"` in place of `import.meta.env.DEV`.\n\n## Plain HTML\n\n```html\n<script src=\"https://cdn.jsdelivr.net/npm/pocketbase@0.28.1/dist/pocketbase.umd.js\"></script>\n<script>\n const pb = new PocketBase(window.location.origin)\n pb.autoCancellation(false)\n</script>\n```\n\n## Local development\n\nThere is one backend, the live one. In development the app talks to it directly (above), not through a dev-server proxy: a proxy works for REST but realtime through it depends on HTTP/1.1 (`troubleshooting.md`). Records created while testing are real data; delete them in the dashboard before handing over, or use a test account. Opening the app from `file://` does not work for same-origin calls; use the dev server.\n\n## Everyday calls\n\n```ts\nconst page = await pb.collection(\"posts\").getList(1, 20, {\n filter: pb.filter(\"published = {:p} && author = {:a}\", { p: true, a: userId }),\n sort: \"-created\",\n expand: \"author\",\n})\nconst all = await pb.collection(\"products\").getFullList({ sort: \"name\" })\nconst one = await pb.collection(\"posts\").getOne(id)\nconst first = await pb.collection(\"rooms\").getFirstListItem(pb.filter(\"slug = {:s}\", { s: slug }))\nconst post = await pb.collection(\"posts\").create({ title, author: pb.authStore.record.id })\nawait pb.collection(\"posts\").update(post.id, { published: true })\nawait pb.collection(\"posts\").delete(post.id)\n```\n\n- Build every filter with `pb.filter(expr, params)`; never put user input into a filter string yourself.\n- `getList` returns `{ items, page, perPage, totalItems, totalPages }`; `perPage` goes up to 1000. Show \"Load more\" with the next `page`, or pass `skipTotal: true` when the count is not needed (faster).\n- `getFullList` fetches every page; use it only for small collections such as a catalog.\n- `expand: \"author\"` puts the related record in `record.expand.author`, but only if the caller may view it under that collection's rules.\n\n## Errors\n\nErrors are `ClientResponseError` with `status` and `response`:\n\n- 400 with `response.data.<field>.message`: show that message next to the field.\n- 400 \"Failed to create record.\" with empty `data`: the create rule rejected it (honeypot filled, wrong owner, room closed). Show a general \"Could not send\" and check the rule.\n- 404 on view, update or delete: not found or not allowed by the rule.\n- 403: the rule is `null` (superusers only).\n- 429: rate limit. Ask the visitor to wait a minute.\n- `status` 0: network error or aborted request.\n\n## Files\n\n```ts\nconst form = new FormData()\nform.append(\"title\", title)\nform.append(\"cover\", fileInput.files[0])\nconst post = await pb.collection(\"posts\").create(form)\nconst url = pb.files.getURL(post, post.cover, { thumb: \"400x300\" })\n```\n\n- Files over the field's `maxSize` (default 5 MB) are rejected with a field error; check `file.size` before uploading.\n- Thumbnails work only for sizes listed in the field's `thumbs`.\n- For `protected` file fields, fetch a token first: `const token = await pb.files.getToken()` and pass `{ token }` to `getURL`. It expires after a few minutes.\n\n## Realtime\n\n```ts\nconst unsubscribe = await pb.collection(\"messages\").subscribe(\n \"*\",\n (event) => {\n if (event.action === \"create\") add(event.record)\n if (event.action === \"update\") replace(event.record)\n if (event.action === \"delete\") remove(event.record.id)\n },\n { filter: pb.filter(\"room = {:room}\", { room: roomId }), expand: \"author\" },\n)\n```\n\n- Load the initial list first, then subscribe, and merge by `id` so nothing shows twice.\n- Call `unsubscribe()` when the view unmounts.\n- `pb.realtime.isConnected` tells whether the stream is up; show a small \"Live\" or \"Connecting\" indicator.\n- Events follow the collection's view rule: a visitor only receives records they may view.\n- An idle backend sleeps after about 5 minutes and wakes on the next request; an open realtime stream keeps it awake. The first request after sleep can take a few seconds or return 503 once, so retry once and keep timeouts at 10 s or more.\n\n## Node.js apps on the same website\n\nA Node.js app on the site can call its own backend at `https://<domain>` for trusted server-side work (webhooks, scheduled jobs, writes visitors must not make):\n\n1. Store `PB_URL`, `PB_SUPERUSER_EMAIL` and `PB_SUPERUSER_PASSWORD` as Node.js environment variables. `hosting_nodejs_replace-environment-variables` replaces the full set, so read the current ones first and send them all.\n2. Do superuser work on its own client in a server-only module (e.g. `src/lib/pb-admin.ts`), used only by that trusted work: authenticate it once at startup with `admin.collection(\"_superusers\").authWithPassword(email, password)` and again on a 401. Never sign in the shared `pb` client: pages rendered and requests handled for visitors would then run as superuser and skip every collection rule. Server code acting for a visitor uses a client with no superuser sign-in (a new `PocketBase` per request when it carries the visitor's own sign-in).\n3. The app's own routes must not start with `/api` or `/_`; those paths go to PocketBase.\n4. For realtime subscriptions from Node.js, check the HTTP/1.1 note in `troubleshooting.md`.\n\n## Routing for single-page apps\n\nPocketBase owns `/api/*` and `/_/*`. If the app uses history routing (`/rooms/42`) on a static deploy, add `public/.htaccess` so unknown paths load `index.html` without catching the backend:\n\n```apache\nRewriteEngine On\nRewriteCond %{REQUEST_URI} !^/(api|_)(/|$)\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^ /index.html [L]\n```\n\nHash routing (`/#/rooms/42`) needs nothing.\n"
|
|
246
246
|
},
|
|
247
247
|
{
|
|
248
248
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/patterns.md",
|
|
@@ -274,24 +274,24 @@ export default [
|
|
|
274
274
|
},
|
|
275
275
|
{
|
|
276
276
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/scripts/pb-apply-schema.mjs",
|
|
277
|
-
"digest": "sha256:
|
|
278
|
-
"size":
|
|
277
|
+
"digest": "sha256:830ed68ca9db9848ac158a6b8976628feefa70d57fcc67d8a5d46d8a438586f5",
|
|
278
|
+
"size": 12542,
|
|
279
279
|
"mimeType": "text/plain",
|
|
280
|
-
"text": "import {\n baseUrlFrom,\n describeError,\n fail,\n listCollections,\n mergeRateLimitRules,\n readCredentials,\n readJson,\n request,\n superuserToken,\n wakeUp,\n} from \"./pb-lib.mjs\"\n\nconst args = process.argv.slice(2)\nconst checkOnly = args.includes(\"--check\")\nconst [schemaPath, credsPath] = args.filter((arg) => arg !== \"--check\")\nif (!schemaPath || (!credsPath && !checkOnly)) {\n fail(\"Usage: node pb-apply-schema.mjs <schema.json> <credentials.json> or node pb-apply-schema.mjs --check <schema.json>\")\n}\n\nconst RULE_KEYS = {\n list: \"listRule\",\n view: \"viewRule\",\n create: \"createRule\",\n update: \"updateRule\",\n delete: \"deleteRule\",\n auth: \"authRule\",\n manage: \"manageRule\",\n}\nconst AUTH_ONLY_RULE_KEYS = new Set([\"auth\", \"manage\"])\nconst COLLECTION_KEYS = new Set([\"name\", \"type\", \"rules\", \"fields\", \"indexes\", \"authOptions\", \"timestamps\", \"viewQuery\", \"seed\"])\nconst COLLECTION_TYPES = new Set([\"base\", \"auth\", \"view\"])\nconst FIELD_TYPES = new Set([\"text\", \"editor\", \"number\", \"bool\", \"email\", \"url\", \"date\", \"autodate\", \"select\", \"file\", \"relation\", \"json\", \"geoPoint\"])\nconst INDEX_NAME = /INDEX\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?[`\"]?(\\w+)[`\"]?/i\nconst TIMESTAMPS = [\n { name: \"created\", type: \"autodate\", onCreate: true, onUpdate: false },\n { name: \"updated\", type: \"autodate\", onCreate: true, onUpdate: true },\n]\n\nconst schema = readJson(schemaPath)\nconst wanted = Array.isArray(schema.collections) ? schema.collections : fail('schema.json needs a top-level \"collections\" array')\nvalidateSchema()\nif (checkOnly) {\n console.log(`OK ${schemaPath} is valid (${wanted.length} collections). Relation targets outside the file are checked when applied.`)\n process.exit(0)\n}\n\nconst creds = readCredentials(credsPath)\nconst base = baseUrlFrom(creds)\nawait wakeUp(base)\nconst token = await superuserToken(base, creds)\n\nconst isView = (collection) => (collection.type ?? \"base\") === \"view\"\nlet collections = await listCollections(base, token)\nawait createMissingCollections(wanted.filter((collection) => !isView(collection)))\ncollections = await listCollections(base, token)\nawait updateFieldsAndIndexes(wanted.filter((collection) => !isView(collection)))\nawait createMissingCollections(wanted.filter(isView))\ncollections = await listCollections(base, token)\nawait updateFieldsAndIndexes(wanted.filter(isView))\nawait applyRules()\nawait applyRateLimits()\nawait seedEmptyCollections()\nconsole.log(`DONE schema applied to ${base}`)\n\nfunction validateSchema() {\n const problems = []\n const names = new Set()\n for (const collection of wanted) {\n const label = collection.name ?? \"(unnamed)\"\n if (!collection.name || !/^[a-z_][a-z0-9_]*$/i.test(collection.name)) problems.push(`invalid collection name \"${collection.name}\"`)\n if (names.has(collection.name)) problems.push(`${label}: listed twice`)\n names.add(collection.name)\n for (const key of Object.keys(collection)) {\n if (!COLLECTION_KEYS.has(key)) problems.push(`${label}: unknown key \"${key}\" (allowed: ${[...COLLECTION_KEYS].join(\", \")})`)\n }\n const type = collection.type ?? \"base\"\n if (!COLLECTION_TYPES.has(type)) problems.push(`${label}: type must be base, auth or view`)\n if (type === \"view\" && !collection.viewQuery) problems.push(`${label}: view collections need \"viewQuery\"`)\n if (type !== \"view\" && collection.viewQuery) problems.push(`${label}: \"viewQuery\" only applies to type \"view\"`)\n for (const key of Object.keys(collection.rules ?? {})) {\n if (!(key in RULE_KEYS)) problems.push(`${label}: unknown rule \"${key}\" (allowed: ${Object.keys(RULE_KEYS).join(\", \")})`)\n if (AUTH_ONLY_RULE_KEYS.has(key) && type !== \"auth\") problems.push(`${label}: rule \"${key}\" only applies to auth collections`)\n const value = collection.rules[key]\n if (value !== null && typeof value !== \"string\") problems.push(`${label}: rule \"${key}\" must be a string or null`)\n }\n if (type === \"view\" && collection.rules) {\n for (const key of [\"create\", \"update\", \"delete\"]) {\n if (key in collection.rules) problems.push(`${label}: view collections are read-only; remove the \"${key}\" rule`)\n }\n }\n for (const field of collection.fields ?? []) {\n if (!field.name) problems.push(`${label}: a field has no name`)\n if (!FIELD_TYPES.has(field.type)) problems.push(`${label}.${field.name}: unknown field type \"${field.type}\"`)\n if (field.type === \"relation\" && !field.collection) problems.push(`${label}.${field.name}: relation fields need \"collection\" (the target collection name)`)\n if (field.type === \"select\" && !(Array.isArray(field.values) && field.values.length)) problems.push(`${label}.${field.name}: select fields need a \"values\" array`)\n }\n if (type === \"view\" && collection.fields?.length) problems.push(`${label}: view collections take their fields from viewQuery; remove \"fields\"`)\n if (collection.seed !== undefined && !Array.isArray(collection.seed)) problems.push(`${label}: \"seed\" must be an array of records`)\n }\n if (schema.rateLimits !== undefined && !Array.isArray(schema.rateLimits)) problems.push('\"rateLimits\" must be an array')\n for (const rule of Array.isArray(schema.rateLimits) ? schema.rateLimits : []) {\n if (!rule?.label || !(rule.maxRequests > 0) || !(rule.duration > 0)) {\n problems.push(`each rateLimits entry needs \"label\", \"maxRequests\" and \"duration\" (seconds): ${JSON.stringify(rule)}`)\n }\n }\n if (problems.length) fail(`schema.json has ${problems.length} problem(s):\\n - ${problems.join(\"\\n - \")}`)\n}\n\nfunction toApiField(field) {\n const { collection, ...rest } = field\n if (field.type !== \"relation\") return rest\n const collectionId = collections.get(collection)?.id\n if (!collectionId) fail(`Relation target \"${collection}\" does not exist. Add it to schema.json or fix the name.`)\n return { maxSelect: 1, cascadeDelete: false, ...rest, collectionId }\n}\n\nfunction mergeFields(existing, desired) {\n const byName = new Map((existing?.fields ?? []).map((field) => [field.name, field]))\n const merged = desired.map((field) => {\n const current = byName.get(field.name)\n if (current && current.type !== field.type) {\n fail(`Field \"${field.name}\" exists with type ${current.type}; changing it to ${field.type} would drop data. Use a new field name instead.`)\n }\n return current ? { ...current, ...field, id: current.id } : field\n })\n const desiredNames = new Set(desired.map((field) => field.name))\n const kept = (existing?.fields ?? []).filter((field) => !desiredNames.has(field.name))\n return [...kept.filter((field) => field.system), ...merged, ...kept.filter((field) => !field.system)]\n}\n\nfunction indexName(sql) {\n return INDEX_NAME.exec(sql)?.[1]\n}\n\nfunction indexDefinition(sql) {\n return sql.replace(INDEX_NAME, \"INDEX\").replace(/[`\"]/g, \"\").replace(/\\s+/g, \" \").trim().toLowerCase()\n}\n\nfunction mergeIndexes(existing, desired) {\n if (!desired) return existing ?? []\n const names = new Set(desired.map(indexName))\n const definitions = new Set(desired.map(indexDefinition))\n const kept = (existing ?? []).filter((sql) => !names.has(indexName(sql)) && !definitions.has(indexDefinition(sql)))\n return [...kept, ...desired]\n}\n\nfunction withTimestamps(collection, fields, existingFields = []) {\n if (collection.timestamps === false) return fields\n const present = (name) => fields.some((field) => field.name === name) || existingFields.some((field) => field.name === name)\n return [...fields, ...TIMESTAMPS.filter((timestamp) => !present(timestamp.name))]\n}\n\nasync function createMissingCollections(group) {\n for (const collection of group) {\n if (collections.has(collection.name)) continue\n const type = collection.type ?? \"base\"\n const body = { name: collection.name, type }\n if (type === \"view\") {\n body.viewQuery = collection.viewQuery\n } else {\n const plainFields = (collection.fields ?? []).filter((field) => field.type !== \"relation\")\n body.fields = withTimestamps(collection, plainFields)\n }\n const res = await request(base, \"/api/collections\", { method: \"POST\", token, body })\n if (res.status !== 200) fail(`Cannot create ${collection.name}: ${describeError(res)}`)\n console.log(`NEW ${collection.name}`)\n }\n}\n\nasync function updateFieldsAndIndexes(group) {\n for (const collection of group) {\n const existing = collections.get(collection.name)\n const body = {}\n if (existing.type === \"view\") {\n if (collection.viewQuery && collection.viewQuery !== existing.viewQuery) body.viewQuery = collection.viewQuery\n } else {\n const desired = withTimestamps(collection, (collection.fields ?? []).map(toApiField), existing.fields)\n body.fields = mergeFields(existing, desired)\n body.indexes = mergeIndexes(existing.indexes, collection.indexes)\n }\n if (collection.authOptions) Object.assign(body, collection.authOptions)\n if (!Object.keys(body).length) continue\n const res = await request(base, `/api/collections/${existing.id}`, { method: \"PATCH\", token, body })\n if (res.status !== 200) fail(`Cannot update ${collection.name}: ${describeError(res)}`)\n console.log(`SYNC ${collection.name} (${res.data.fields.length} fields, ${res.data.indexes.length} indexes)`)\n }\n}\n\nasync function applyRules() {\n for (const collection of wanted) {\n if (!collection.rules) continue\n const body = {}\n for (const [key, apiKey] of Object.entries(RULE_KEYS)) {\n if (key in collection.rules) body[apiKey] = collection.rules[key]\n }\n const res = await request(base, `/api/collections/${collections.get(collection.name).id}`, { method: \"PATCH\", token, body })\n if (res.status !== 200) fail(`Cannot set rules on ${collection.name}: ${describeError(res)}`)\n console.log(`RULES ${collection.name}`)\n }\n}\n\nasync function applyRateLimits() {\n if (!schema.rateLimits?.length) return\n const settings = await request(base, \"/api/settings\", { token })\n if (settings.status !== 200) fail(`Cannot read settings: ${describeError(settings)}`)\n const current = settings.data.rateLimits ?? { enabled: true, rules: [] }\n const rules = mergeRateLimitRules(current.rules ?? [], schema.rateLimits)\n const res = await request(base, \"/api/settings\", { method: \"PATCH\", token, body: { rateLimits: { ...current, enabled: true, rules } } })\n if (res.status !== 200) fail(`Cannot set rate limits: ${describeError(res)}`)\n console.log(`LIMIT ${schema.rateLimits.map((rule) => rule.label).join(\", \")}`)\n}\n\nasync function seedEmptyCollections() {\n for (const collection of wanted) {\n if (!collection.seed?.length) continue\n const recordsPath = `/api/collections/${collection.name}/records`\n const count = await request(base, `${recordsPath}?perPage=1&skipTotal=0`, { token })\n if (count.status !== 200) fail(`Cannot read ${collection.name}: ${describeError(count)}`)\n if (count.data.totalItems > 0) {\n console.log(`SEED ${collection.name} skipped (already has ${count.data.totalItems} records)`)\n continue\n }\n const inserted = []\n for (const record of collection.seed) {\n const res = await request(base, recordsPath, { method: \"POST\", token, body: record })\n if (res.status === 200) {\n inserted.push(res.data.id)\n continue\n }\n await removeRecords(recordsPath, inserted)\n const after = await request(base, `${recordsPath}?perPage=1&skipTotal=0`, { token })\n const left = after.status === 200 ? after.data.totalItems : null\n const cleanup = left === 0\n ? \"\"\n : ` ${left ?? \"Some\"} record(s) are still in ${collection.name} (a request that failed may still have been saved); delete them in the dashboard, or the next run skips this collection's seed.`\n fail(`Cannot seed ${collection.name} with ${JSON.stringify(record)}: ${describeError(res)}.${cleanup}`)\n }\n console.log(`SEED ${collection.name} (${collection.seed.length} records)`)\n }\n}\n\nasync function removeRecords(recordsPath, ids) {\n for (const id of ids) await request(base, `${recordsPath}/${id}`, { method: \"DELETE\", token })\n}\n"
|
|
280
|
+
"text": "import {\n baseUrlFrom,\n describeError,\n fail,\n listCollections,\n mergeRateLimitRules,\n readCredentials,\n readJson,\n request,\n superuserToken,\n wakeUp,\n} from \"./pb-lib.mjs\"\n\nconst args = process.argv.slice(2)\nconst checkOnly = args.includes(\"--check\")\nconst [schemaPath, credsPath] = args.filter((arg) => arg !== \"--check\")\nif (!schemaPath || (!credsPath && !checkOnly)) {\n fail(\"Usage: node pb-apply-schema.mjs <schema.json> <credentials.json> or node pb-apply-schema.mjs --check <schema.json>\")\n}\n\nconst RULE_KEYS = {\n list: \"listRule\",\n view: \"viewRule\",\n create: \"createRule\",\n update: \"updateRule\",\n delete: \"deleteRule\",\n auth: \"authRule\",\n manage: \"manageRule\",\n}\nconst AUTH_ONLY_RULE_KEYS = new Set([\"auth\", \"manage\"])\nconst COLLECTION_KEYS = new Set([\"name\", \"type\", \"rules\", \"fields\", \"indexes\", \"authOptions\", \"timestamps\", \"viewQuery\", \"seed\"])\nconst COLLECTION_TYPES = new Set([\"base\", \"auth\", \"view\"])\nconst FIELD_TYPES = new Set([\"text\", \"editor\", \"number\", \"bool\", \"email\", \"url\", \"date\", \"autodate\", \"select\", \"file\", \"relation\", \"json\", \"geoPoint\"])\nconst INDEX_NAME = /INDEX\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?[`\"]?(\\w+)[`\"]?/i\nconst TIMESTAMPS = [\n { name: \"created\", type: \"autodate\", onCreate: true, onUpdate: false },\n { name: \"updated\", type: \"autodate\", onCreate: true, onUpdate: true },\n]\n\nconst schema = readJson(schemaPath)\nconst wanted = Array.isArray(schema.collections) ? schema.collections : fail('schema.json needs a top-level \"collections\" array')\nvalidateSchema()\nif (checkOnly) {\n console.log(`OK ${schemaPath} is valid (${wanted.length} collections). Relation targets outside the file are checked when applied.`)\n process.exit(0)\n}\n\nconst creds = readCredentials(credsPath)\nconst base = baseUrlFrom(creds)\nawait wakeUp(base)\nconst token = await superuserToken(base, creds)\n\nconst isView = (collection) => (collection.type ?? \"base\") === \"view\"\nlet collections = await listCollections(base, token)\nawait createMissingCollections(wanted.filter((collection) => !isView(collection)))\ncollections = await listCollections(base, token)\nawait updateFieldsAndIndexes(wanted.filter((collection) => !isView(collection)))\nawait createMissingCollections(wanted.filter(isView))\ncollections = await listCollections(base, token)\nawait updateFieldsAndIndexes(wanted.filter(isView))\nawait applyRules()\nawait applyRateLimits()\nawait seedEmptyCollections()\nconsole.log(`DONE schema applied to ${base}`)\n\nfunction validateSchema() {\n const problems = []\n const names = new Set()\n for (const collection of wanted) {\n const label = collection.name ?? \"(unnamed)\"\n if (!collection.name || !/^[a-z_][a-z0-9_]*$/i.test(collection.name)) problems.push(`invalid collection name \"${collection.name}\"`)\n if (names.has(collection.name)) problems.push(`${label}: listed twice`)\n names.add(collection.name)\n for (const key of Object.keys(collection)) {\n if (!COLLECTION_KEYS.has(key)) problems.push(`${label}: unknown key \"${key}\" (allowed: ${[...COLLECTION_KEYS].join(\", \")})`)\n }\n const type = collection.type ?? \"base\"\n if (!COLLECTION_TYPES.has(type)) problems.push(`${label}: type must be base, auth or view`)\n if (type === \"view\" && !collection.viewQuery) problems.push(`${label}: view collections need \"viewQuery\"`)\n if (type !== \"view\" && collection.viewQuery) problems.push(`${label}: \"viewQuery\" only applies to type \"view\"`)\n for (const key of Object.keys(collection.rules ?? {})) {\n if (!(key in RULE_KEYS)) problems.push(`${label}: unknown rule \"${key}\" (allowed: ${Object.keys(RULE_KEYS).join(\", \")})`)\n if (AUTH_ONLY_RULE_KEYS.has(key) && type !== \"auth\") problems.push(`${label}: rule \"${key}\" only applies to auth collections`)\n const value = collection.rules[key]\n if (value !== null && typeof value !== \"string\") problems.push(`${label}: rule \"${key}\" must be a string or null`)\n }\n if (type === \"view\" && collection.rules) {\n for (const key of [\"create\", \"update\", \"delete\"]) {\n if (key in collection.rules) problems.push(`${label}: view collections are read-only; remove the \"${key}\" rule`)\n }\n }\n for (const field of collection.fields ?? []) {\n if (!field.name) problems.push(`${label}: a field has no name`)\n if (!FIELD_TYPES.has(field.type)) problems.push(`${label}.${field.name}: unknown field type \"${field.type}\"`)\n if (field.type === \"relation\" && !field.collection) problems.push(`${label}.${field.name}: relation fields need \"collection\" (the target collection name)`)\n if (field.type === \"select\" && !(Array.isArray(field.values) && field.values.length)) problems.push(`${label}.${field.name}: select fields need a \"values\" array`)\n }\n if (type === \"view\" && collection.fields?.length) problems.push(`${label}: view collections take their fields from viewQuery; remove \"fields\"`)\n if (collection.seed !== undefined && !Array.isArray(collection.seed)) problems.push(`${label}: \"seed\" must be an array of records`)\n }\n if (schema.rateLimits !== undefined && !Array.isArray(schema.rateLimits)) problems.push('\"rateLimits\" must be an array')\n for (const rule of Array.isArray(schema.rateLimits) ? schema.rateLimits : []) {\n if (!rule?.label || !(rule.maxRequests > 0) || !(rule.duration > 0)) {\n problems.push(`each rateLimits entry needs \"label\", \"maxRequests\" and \"duration\" (seconds): ${JSON.stringify(rule)}`)\n }\n }\n if (problems.length) fail(`schema.json has ${problems.length} problem(s):\\n - ${problems.join(\"\\n - \")}`)\n}\n\nfunction toApiField(field) {\n const { collection, ...rest } = field\n if (field.type !== \"relation\") return rest\n const collectionId = collections.get(collection)?.id\n if (!collectionId) fail(`Relation target \"${collection}\" does not exist. Add it to schema.json or fix the name.`)\n return { maxSelect: 1, cascadeDelete: false, ...rest, collectionId }\n}\n\nfunction mergeFields(existing, desired) {\n const byName = new Map((existing?.fields ?? []).map((field) => [field.name, field]))\n const merged = desired.map((field) => {\n const current = byName.get(field.name)\n if (current && current.type !== field.type) {\n fail(`Field \"${field.name}\" exists with type ${current.type}; changing it to ${field.type} would drop data. Use a new field name instead.`)\n }\n return current ? { ...current, ...field, id: current.id } : field\n })\n const desiredNames = new Set(desired.map((field) => field.name))\n const kept = (existing?.fields ?? []).filter((field) => !desiredNames.has(field.name))\n return [...kept.filter((field) => field.system), ...merged, ...kept.filter((field) => !field.system)]\n}\n\nfunction indexName(sql) {\n return INDEX_NAME.exec(sql)?.[1]\n}\n\nfunction indexDefinition(sql) {\n return sql.replace(INDEX_NAME, \"INDEX\").replace(/[`\"]/g, \"\").replace(/\\s+/g, \" \").trim().toLowerCase()\n}\n\nfunction mergeIndexes(existing, desired) {\n if (!desired) return existing ?? []\n const names = new Set(desired.map(indexName))\n const definitions = new Set(desired.map(indexDefinition))\n const kept = (existing ?? []).filter((sql) => !names.has(indexName(sql)) && !definitions.has(indexDefinition(sql)))\n return [...kept, ...desired]\n}\n\nfunction withTimestamps(collection, fields, existingFields = []) {\n if (collection.timestamps === false) return fields\n const present = (name) => fields.some((field) => field.name === name) || existingFields.some((field) => field.name === name)\n return [...fields, ...TIMESTAMPS.filter((timestamp) => !present(timestamp.name))]\n}\n\nasync function createMissingCollections(group) {\n for (const collection of group) {\n if (collections.has(collection.name)) continue\n const type = collection.type ?? \"base\"\n const body = { name: collection.name, type }\n if (type === \"view\") {\n body.viewQuery = collection.viewQuery\n } else {\n const plainFields = (collection.fields ?? []).filter((field) => field.type !== \"relation\")\n body.fields = withTimestamps(collection, plainFields)\n }\n const res = await request(base, \"/api/collections\", { method: \"POST\", token, body })\n if (res.status !== 200) fail(`Cannot create ${collection.name}: ${describeError(res)}`)\n console.log(`NEW ${collection.name}`)\n }\n}\n\nasync function updateFieldsAndIndexes(group) {\n for (const collection of group) {\n const existing = collections.get(collection.name)\n const body = {}\n if (existing.type === \"view\") {\n if (collection.viewQuery && collection.viewQuery !== existing.viewQuery) body.viewQuery = collection.viewQuery\n } else {\n const desired = withTimestamps(collection, (collection.fields ?? []).map(toApiField), existing.fields)\n body.fields = mergeFields(existing, desired)\n body.indexes = mergeIndexes(existing.indexes, collection.indexes)\n // A new field is writable under the old rules until applyRules() runs (it goes last because rules\n // may name fields of collections synced later), so lock the writes it will replace meanwhile. An\n // aborted run then leaves them superuser-only, not open.\n if (desired.some((field) => !existing.fields.some((f) => f.name === field.name))) {\n for (const key of [\"create\", \"update\"]) {\n if (key in (collection.rules ?? {})) body[RULE_KEYS[key]] = null\n }\n }\n }\n if (collection.authOptions) Object.assign(body, collection.authOptions)\n if (!Object.keys(body).length) continue\n const res = await request(base, `/api/collections/${existing.id}`, { method: \"PATCH\", token, body })\n if (res.status !== 200) fail(`Cannot update ${collection.name}: ${describeError(res)}`)\n console.log(`SYNC ${collection.name} (${res.data.fields.length} fields, ${res.data.indexes.length} indexes)`)\n }\n}\n\nasync function applyRules() {\n for (const collection of wanted) {\n if (!collection.rules) continue\n const body = {}\n for (const [key, apiKey] of Object.entries(RULE_KEYS)) {\n if (key in collection.rules) body[apiKey] = collection.rules[key]\n }\n const res = await request(base, `/api/collections/${collections.get(collection.name).id}`, { method: \"PATCH\", token, body })\n if (res.status !== 200) fail(`Cannot set rules on ${collection.name}: ${describeError(res)}`)\n console.log(`RULES ${collection.name}`)\n }\n}\n\nasync function applyRateLimits() {\n if (!schema.rateLimits?.length) return\n const settings = await request(base, \"/api/settings\", { token })\n if (settings.status !== 200) fail(`Cannot read settings: ${describeError(settings)}`)\n const current = settings.data.rateLimits ?? { enabled: true, rules: [] }\n const rules = mergeRateLimitRules(current.rules ?? [], schema.rateLimits)\n const res = await request(base, \"/api/settings\", { method: \"PATCH\", token, body: { rateLimits: { ...current, enabled: true, rules } } })\n if (res.status !== 200) fail(`Cannot set rate limits: ${describeError(res)}`)\n console.log(`LIMIT ${schema.rateLimits.map((rule) => rule.label).join(\", \")}`)\n}\n\nasync function seedEmptyCollections() {\n for (const collection of wanted) {\n if (!collection.seed?.length) continue\n const recordsPath = `/api/collections/${collection.name}/records`\n const count = await request(base, `${recordsPath}?perPage=1&skipTotal=0`, { token })\n if (count.status !== 200) fail(`Cannot read ${collection.name}: ${describeError(count)}`)\n if (count.data.totalItems > 0) {\n console.log(`SEED ${collection.name} skipped (already has ${count.data.totalItems} records)`)\n continue\n }\n const inserted = []\n for (const record of collection.seed) {\n const res = await request(base, recordsPath, { method: \"POST\", token, body: record })\n if (res.status === 200) {\n inserted.push(res.data.id)\n continue\n }\n await removeRecords(recordsPath, inserted)\n const after = await request(base, `${recordsPath}?perPage=1&skipTotal=0`, { token })\n const left = after.status === 200 ? after.data.totalItems : null\n const cleanup = left === 0\n ? \"\"\n : ` ${left ?? \"Some\"} record(s) are still in ${collection.name} (a request that failed may still have been saved); delete them in the dashboard, or the next run skips this collection's seed.`\n fail(`Cannot seed ${collection.name} with ${JSON.stringify(record)}: ${describeError(res)}.${cleanup}`)\n }\n console.log(`SEED ${collection.name} (${collection.seed.length} records)`)\n }\n}\n\nasync function removeRecords(recordsPath, ids) {\n for (const id of ids) await request(base, `${recordsPath}/${id}`, { method: \"DELETE\", token })\n}\n"
|
|
281
281
|
},
|
|
282
282
|
{
|
|
283
283
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/scripts/pb-lib.mjs",
|
|
284
|
-
"digest": "sha256:
|
|
285
|
-
"size":
|
|
284
|
+
"digest": "sha256:f4c95240fb7203c9b7ef11c007961524f71524e4391cde0bca8e25cffaee50e6",
|
|
285
|
+
"size": 4703,
|
|
286
286
|
"mimeType": "text/plain",
|
|
287
|
-
"text": "import fs from \"node:fs\"\n\nconst REQUEST_TIMEOUT_MS = 20000\nconst WAKE_UP_RETRY_DELAY_MS = 3000\nconst RETRYABLE_STATUSES = new Set([502, 503, 504])\nconst RETRYABLE_STATUSES_FOR_WRITES = new Set([503])\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\"])\n\nexport function readJson(path) {\n try {\n return JSON.parse(fs.readFileSync(path, \"utf8\"))\n } catch (error) {\n fail(`Cannot read ${path}: ${error.message}`)\n }\n}\n\nexport function readCredentials(path) {\n const creds = readJson(path)\n const mode = fs.statSync(path).mode\n const readableByOthers = (mode & 0o077) !== 0\n if (readableByOthers && process.platform !== \"win32\") {\n console.warn(`WARN ${path} is readable by other users; run: chmod 600 ${path}`)\n }\n return creds\n}\n\nexport function fail(message) {\n console.error(`ERROR ${message}`)\n process.exit(1)\n}\n\nexport function baseUrlFrom(creds) {\n const raw = creds.api_url ?? (creds.domain ? `https://${creds.domain}` : null)\n if (!raw) fail(\"The credentials file has no domain or api_url. Save the full hosting_pocketbase_create-backend response.\")\n const withScheme = /^https?:\\/\\//i.test(raw) ? raw : `https://${raw}`\n return withScheme.replace(/\\/+$/, \"\").replace(/\\/api$/i, \"\")\n}\n\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n\nexport async function request(base, path, { method = \"GET\", token, body, retries = 2 } = {}) {\n const canRetryNetworkErrors = SAFE_METHODS.has(method)\n const retryableStatuses = SAFE_METHODS.has(method) ? RETRYABLE_STATUSES : RETRYABLE_STATUSES_FOR_WRITES\n let lastError\n for (let attempt = 0; attempt <= retries; attempt++) {\n const isLastAttempt = attempt === retries\n try {\n const response = await fetch(`${base}${path}`, {\n method,\n headers: {\n Accept: \"application/json\",\n ...(body ? { \"Content-Type\": \"application/json\" } : {}),\n ...(token ? { Authorization: token } : {}),\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n if (retryableStatuses.has(response.status) && !isLastAttempt) {\n await sleep(WAKE_UP_RETRY_DELAY_MS)\n continue\n }\n const text = await response.text()\n let data = null\n try {\n data = text ? JSON.parse(text) : null\n } catch {\n data = text\n }\n return { status: response.status, data }\n } catch (error) {\n lastError = error\n if (!canRetryNetworkErrors || isLastAttempt) break\n await sleep(WAKE_UP_RETRY_DELAY_MS)\n }\n }\n return { status: 0, data: { message: lastError?.message ?? \"request failed\" } }\n}\n\nexport async function wakeUp(base) {\n const health = await request(base, \"/api/health\", { retries: 5 })\n if (health.status !== 200) {\n fail(`${base}/api/health returned ${health.status} (${health.data?.message ?? \"no message\"}). Check the domain and that the backend exists (hosting_pocketbase_backend).`)\n }\n}\n\nexport async function superuserToken(base, creds) {\n const email = creds.superuser_email\n const password = creds.superuser_password\n if (!email || !password) fail(\"The credentials file has no superuser_email or superuser_password.\")\n const res = await request(base, \"/api/collections/_superusers/auth-with-password\", {\n method: \"POST\",\n body: { identity: email, password },\n retries: 4,\n })\n if (res.status !== 200) {\n fail(\n `Superuser sign-in failed (${res.status}: ${res.data?.message ?? \"no message\"}). ` +\n \"If the password was lost, rotate it with hosting_pocketbase_set-superuser and save the response.\",\n )\n }\n return res.data.token\n}\n\nexport async function listCollections(base, token) {\n const res = await request(base, \"/api/collections?perPage=1000\", { token })\n if (res.status !== 200) fail(`Cannot list collections: ${describeError(res)}`)\n return new Map(res.data.items.map((item) => [item.name, item]))\n}\n\nexport function describeError(res) {\n const details = res.data?.data && Object.keys(res.data.data).length ? JSON.stringify(res.data.data) : \"\"\n return `${res.status} ${res.data?.message ?? \"\"} ${details}`.trim()\n}\n\nexport function mergeRateLimitRules(current, desired) {\n const keyOf = (rule) => `${rule.label}|${rule.audience ?? \"\"}`\n const desiredKeys = new Set(desired.map(keyOf))\n const normalized = desired.map((rule) => ({ audience: \"\", ...rule }))\n return [...current.filter((rule) => !desiredKeys.has(keyOf(rule))), ...normalized]\n}\n"
|
|
287
|
+
"text": "import fs from \"node:fs\"\n\nconst REQUEST_TIMEOUT_MS = 20000\nconst WAKE_UP_RETRY_DELAY_MS = 3000\nconst RETRYABLE_STATUSES = new Set([502, 503, 504])\nconst RETRYABLE_STATUSES_FOR_WRITES = new Set([503])\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\"])\n\nexport function readJson(path) {\n try {\n return JSON.parse(fs.readFileSync(path, \"utf8\"))\n } catch (error) {\n fail(`Cannot read ${path}: ${error.message}`)\n }\n}\n\nexport function readCredentials(path) {\n const creds = readJson(path)\n const mode = fs.statSync(path).mode\n const readableByOthers = (mode & 0o077) !== 0\n if (readableByOthers && process.platform !== \"win32\") {\n try {\n fs.chmodSync(path, 0o600)\n console.warn(`WARN ${path} was readable by other users; it is now mode 600. If this computer is shared, rotate the password with hosting_pocketbase_set-superuser.`)\n } catch {\n console.warn(`WARN ${path} is readable by other users; run: chmod 600 ${path}`)\n }\n }\n return creds\n}\n\nexport function fail(message) {\n console.error(`ERROR ${message}`)\n process.exit(1)\n}\n\nexport function baseUrlFrom(creds) {\n const raw = creds.api_url ?? (creds.domain ? `https://${creds.domain}` : null)\n if (!raw) fail(\"The credentials file has no domain or api_url. Save the full hosting_pocketbase_create-backend response.\")\n const withScheme = /^https?:\\/\\//i.test(raw) ? raw : `https://${raw}`\n return withScheme.replace(/\\/+$/, \"\").replace(/\\/api$/i, \"\")\n}\n\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n\nexport async function request(base, path, { method = \"GET\", token, body, retries = 2 } = {}) {\n const canRetryNetworkErrors = SAFE_METHODS.has(method)\n const retryableStatuses = SAFE_METHODS.has(method) ? RETRYABLE_STATUSES : RETRYABLE_STATUSES_FOR_WRITES\n let lastError\n for (let attempt = 0; attempt <= retries; attempt++) {\n const isLastAttempt = attempt === retries\n try {\n const response = await fetch(`${base}${path}`, {\n method,\n headers: {\n Accept: \"application/json\",\n ...(body ? { \"Content-Type\": \"application/json\" } : {}),\n ...(token ? { Authorization: token } : {}),\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n if (retryableStatuses.has(response.status) && !isLastAttempt) {\n await sleep(WAKE_UP_RETRY_DELAY_MS)\n continue\n }\n const text = await response.text()\n let data = null\n try {\n data = text ? JSON.parse(text) : null\n } catch {\n data = text\n }\n return { status: response.status, data }\n } catch (error) {\n lastError = error\n if (!canRetryNetworkErrors || isLastAttempt) break\n await sleep(WAKE_UP_RETRY_DELAY_MS)\n }\n }\n return { status: 0, data: { message: lastError?.message ?? \"request failed\" } }\n}\n\nexport async function wakeUp(base) {\n const health = await request(base, \"/api/health\", { retries: 5 })\n if (health.status !== 200) {\n fail(`${base}/api/health returned ${health.status} (${health.data?.message ?? \"no message\"}). Check the domain and that the backend exists (hosting_pocketbase_backend).`)\n }\n}\n\nexport async function superuserToken(base, creds) {\n const email = creds.superuser_email\n const password = creds.superuser_password\n if (!email || !password) fail(\"The credentials file has no superuser_email or superuser_password.\")\n const res = await request(base, \"/api/collections/_superusers/auth-with-password\", {\n method: \"POST\",\n body: { identity: email, password },\n retries: 4,\n })\n if (res.status !== 200) {\n fail(\n `Superuser sign-in failed (${res.status}: ${res.data?.message ?? \"no message\"}). ` +\n \"If the password was lost, rotate it with hosting_pocketbase_set-superuser and save the response.\",\n )\n }\n return res.data.token\n}\n\nexport async function listCollections(base, token) {\n const res = await request(base, \"/api/collections?perPage=1000\", { token })\n if (res.status !== 200) fail(`Cannot list collections: ${describeError(res)}`)\n return new Map(res.data.items.map((item) => [item.name, item]))\n}\n\nexport function describeError(res) {\n const details = res.data?.data && Object.keys(res.data.data).length ? JSON.stringify(res.data.data) : \"\"\n return `${res.status} ${res.data?.message ?? \"\"} ${details}`.trim()\n}\n\nexport function mergeRateLimitRules(current, desired) {\n const keyOf = (rule) => `${rule.label}|${rule.audience ?? \"\"}`\n const desiredKeys = new Set(desired.map(keyOf))\n const normalized = desired.map((rule) => ({ audience: \"\", ...rule }))\n return [...current.filter((rule) => !desiredKeys.has(keyOf(rule))), ...normalized]\n}\n"
|
|
288
288
|
},
|
|
289
289
|
{
|
|
290
290
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/scripts/pb-verify.mjs",
|
|
291
|
-
"digest": "sha256:
|
|
292
|
-
"size":
|
|
291
|
+
"digest": "sha256:9d884d1cdedce1b25776e42e81d9ef87c3b2e17690cb7619e12b8e50b24660e1",
|
|
292
|
+
"size": 6427,
|
|
293
293
|
"mimeType": "text/plain",
|
|
294
|
-
"text": "import { execFileSync } from \"node:child_process\"\nimport { baseUrlFrom, listCollections, readCredentials, readJson, request, superuserToken } from \"./pb-lib.mjs\"\n\nconst REALTIME_PROBE_SECONDS = \"8\"\nconst PAGE_TIMEOUT_MS = 15000\n\nconst [credsPath, schemaPath] = process.argv.slice(2)\nif (!credsPath) {\n console.error(\"Usage: node pb-verify.mjs <credentials.json> [schema.json]\")\n process.exit(1)\n}\n\nconst creds = readCredentials(credsPath)\nconst schema = schemaPath ? readJson(schemaPath) : { collections: [] }\nconst base = baseUrlFrom(creds)\nlet failures = 0\nlet warnings = 0\n\nconst pass = (message) => console.log(`PASS ${message}`)\nconst warn = (message) => {\n warnings++\n console.log(`WARN ${message}`)\n}\nconst bad = (message) => {\n failures++\n console.log(`FAIL ${message}`)\n}\n\nconst health = await request(base, \"/api/health\", { retries: 5 })\nif (health.status !== 200) {\n bad(`/api/health returned ${health.status}; the backend is missing or still waking up. Retry in 10 s, then check hosting_pocketbase_backend.`)\n finish()\n}\npass(\"API is healthy\")\n\nconst token = await superuserToken(base, creds)\npass(\"superuser sign-in works\")\n\nconst byName = await listCollections(base, token)\n\nfor (const collection of schema.collections ?? []) {\n const live = byName.get(collection.name)\n if (!live) {\n bad(`collection ${collection.name} is missing; run pb-apply-schema.mjs`)\n continue\n }\n const missing = (collection.fields ?? []).filter((field) => !live.fields.some((f) => f.name === field.name)).map((f) => f.name)\n if (missing.length) bad(`${collection.name} is missing fields: ${missing.join(\", \")}`)\n else if (live.type !== \"view\") pass(`${collection.name} has all ${collection.fields?.length ?? 0} declared fields`)\n\n const timestampsWanted = collection.timestamps !== false && live.type !== \"view\"\n if (timestampsWanted && !live.fields.some((field) => field.name === \"created\")) {\n warn(`${collection.name} has no \"created\" field, so sort: \"-created\" fails; re-run pb-apply-schema.mjs`)\n }\n\n const recordsPath = `/api/collections/${collection.name}/records`\n const anonList = await request(base, `${recordsPath}?perPage=1`)\n if (live.listRule === null) {\n anonList.status === 403\n ? pass(`${collection.name}: visitors cannot list (superusers only)`)\n : bad(`${collection.name}: listRule is null but an anonymous list returned ${anonList.status}`)\n } else if (anonList.status === 200) {\n const scope = live.listRule === \"\" ? \"everyone\" : `rule \"${live.listRule}\"`\n pass(`${collection.name}: listing works, filtered by ${scope}`)\n } else {\n bad(`${collection.name}: anonymous list returned ${anonList.status} ${anonList.data?.message ?? \"\"}`)\n }\n\n if (live.type !== \"view\" && live.createRule === null) {\n const anonCreate = await request(base, recordsPath, { method: \"POST\", body: {} })\n anonCreate.status === 403\n ? pass(`${collection.name}: visitors cannot create`)\n : bad(`${collection.name}: createRule is null but an anonymous create returned ${anonCreate.status}`)\n }\n if (live.createRule === \"\" && live.type === \"base\") warn(`${collection.name}: anyone can create records; fine for a public form, otherwise tighten it`)\n if (live.updateRule === \"\" || live.deleteRule === \"\") warn(`${collection.name}: anyone can update or delete any record; this is almost never intended`)\n}\n\nconst settings = await request(base, \"/api/settings\", { token })\nconst limits = settings.data?.rateLimits\nif (limits?.enabled) {\n const summary = (limits.rules ?? []).map((rule) => `${rule.label}${rule.audience ? ` ${rule.audience}` : \"\"} ${rule.maxRequests}/${rule.duration}s`).join(\", \")\n pass(`rate limits per IP: ${summary}`)\n}\nif (settings.data?.smtp && !settings.data.smtp.enabled) {\n console.log(\"INFO outgoing mail (SMTP) is off: verification and password-reset emails are not sent\")\n}\n\nfunction probeRealtime(protocol) {\n try {\n const out = execFileSync(\"curl\", [\"-sS\", \"-N\", protocol, \"--max-time\", REALTIME_PROBE_SECONDS, \"-H\", \"Accept: text/event-stream\", `${base}/api/realtime`], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n return out.includes(\"PB_CONNECT\") ? \"ok\" : \"no-event\"\n } catch (error) {\n if (error.code === \"ENOENT\") return \"no-curl\"\n return String(error.stdout ?? \"\").includes(\"PB_CONNECT\") ? \"ok\" : \"no-event\"\n }\n}\n\nconst http2 = probeRealtime(\"--http2\")\nif (http2 === \"no-curl\") {\n warn(\"curl is not installed, so realtime was not checked; open the site in two tabs and check a change appears in both\")\n} else {\n http2 === \"ok\" ? pass(\"realtime connects over HTTP/2 (browsers)\") : bad(\"realtime does not connect over HTTP/2; see troubleshooting.md\")\n probeRealtime(\"--http1.1\") === \"ok\"\n ? pass(\"realtime connects over HTTP/1.1 (Node.js clients, dev proxies)\")\n : warn(\"realtime does not connect over HTTP/1.1: browsers are fine, Node.js subscribers need the workaround in troubleshooting.md\")\n}\n\nconst dashboard = await fetch(`${base}/_/`, { signal: AbortSignal.timeout(PAGE_TIMEOUT_MS) }).catch(() => null)\ndashboard?.status === 200 ? pass(`dashboard is at ${base}/_/`) : bad(`dashboard returned ${dashboard?.status ?? \"no response\"}`)\n\nconst home = await fetch(`${base}/`, { signal: AbortSignal.timeout(PAGE_TIMEOUT_MS) }).catch(() => null)\nconst homeText = home ? await home.text() : \"\"\nif (!home || home.status >= 400) bad(`the website itself returned ${home?.status ?? \"no response\"}; deploy the frontend`)\nelse if (/<title>\\s*Coming soon\\s*<\\/title>/i.test(homeText)) {\n warn(\"the website still shows Hostinger's placeholder page; deploy the frontend\")\n} else pass(\"the website is serving the app\")\n\nfinish()\n\nfunction finish() {\n console.log(`\\n${failures ? \"NOT READY\" : \"READY\"}: ${failures} failed, ${warnings} warnings`)\n process.exit(failures ? 1 : 0)\n}\n"
|
|
294
|
+
"text": "import { execFileSync } from \"node:child_process\"\nimport { homedir } from \"node:os\"\nimport path from \"node:path\"\nimport { baseUrlFrom, listCollections, readCredentials, readJson, request, superuserToken } from \"./pb-lib.mjs\"\n\nconst REALTIME_PROBE_SECONDS = \"8\"\nconst PAGE_TIMEOUT_MS = 15000\n\nconst [credsPath, schemaPath] = process.argv.slice(2)\nif (!credsPath) {\n console.error(\"Usage: node pb-verify.mjs <credentials.json> [schema.json]\")\n process.exit(1)\n}\n\nconst creds = readCredentials(credsPath)\nconst schema = schemaPath ? readJson(schemaPath) : { collections: [] }\nconst base = baseUrlFrom(creds)\nlet failures = 0\nlet warnings = 0\n\nconst pass = (message) => console.log(`PASS ${message}`)\nconst warn = (message) => {\n warnings++\n console.log(`WARN ${message}`)\n}\nconst bad = (message) => {\n failures++\n console.log(`FAIL ${message}`)\n}\n\nconst health = await request(base, \"/api/health\", { retries: 5 })\nif (health.status !== 200) {\n bad(`/api/health returned ${health.status}; the backend is missing or still waking up. Retry in 10 s, then check hosting_pocketbase_backend.`)\n finish()\n}\npass(\"API is healthy\")\n\nconst token = await superuserToken(base, creds)\npass(\"superuser sign-in works\")\n\nconst byName = await listCollections(base, token)\n\nfor (const collection of schema.collections ?? []) {\n const live = byName.get(collection.name)\n if (!live) {\n bad(`collection ${collection.name} is missing; run pb-apply-schema.mjs`)\n continue\n }\n const missing = (collection.fields ?? []).filter((field) => !live.fields.some((f) => f.name === field.name)).map((f) => f.name)\n if (missing.length) bad(`${collection.name} is missing fields: ${missing.join(\", \")}`)\n else if (live.type !== \"view\") pass(`${collection.name} has all ${collection.fields?.length ?? 0} declared fields`)\n\n const timestampsWanted = collection.timestamps !== false && live.type !== \"view\"\n if (timestampsWanted && !live.fields.some((field) => field.name === \"created\")) {\n warn(`${collection.name} has no \"created\" field, so sort: \"-created\" fails; re-run pb-apply-schema.mjs`)\n }\n\n const recordsPath = `/api/collections/${collection.name}/records`\n const anonList = await request(base, `${recordsPath}?perPage=1`)\n if (live.listRule === null) {\n anonList.status === 403\n ? pass(`${collection.name}: visitors cannot list (superusers only)`)\n : bad(`${collection.name}: listRule is null but an anonymous list returned ${anonList.status}`)\n } else if (anonList.status === 200) {\n const scope = live.listRule === \"\" ? \"everyone\" : `rule \"${live.listRule}\"`\n pass(`${collection.name}: listing works, filtered by ${scope}`)\n } else {\n bad(`${collection.name}: anonymous list returned ${anonList.status} ${anonList.data?.message ?? \"\"}`)\n }\n\n if (live.type !== \"view\" && live.createRule === null) {\n const anonCreate = await request(base, recordsPath, { method: \"POST\", body: {} })\n anonCreate.status === 403\n ? pass(`${collection.name}: visitors cannot create`)\n : bad(`${collection.name}: createRule is null but an anonymous create returned ${anonCreate.status}`)\n }\n if (live.createRule === \"\" && live.type === \"base\") warn(`${collection.name}: anyone can create records; fine for a public form, otherwise tighten it`)\n if (live.updateRule === \"\" || live.deleteRule === \"\") warn(`${collection.name}: anyone can update or delete any record; this is almost never intended`)\n}\n\nconst settings = await request(base, \"/api/settings\", { token })\nconst limits = settings.data?.rateLimits\nif (limits?.enabled) {\n const summary = (limits.rules ?? []).map((rule) => `${rule.label}${rule.audience ? ` ${rule.audience}` : \"\"} ${rule.maxRequests}/${rule.duration}s`).join(\", \")\n pass(`rate limits per IP: ${summary}`)\n}\nif (settings.data?.smtp && !settings.data.smtp.enabled) {\n console.log(\"INFO outgoing mail (SMTP) is off: verification and password-reset emails are not sent\")\n}\n\n// curl is found by name, and Windows looks in the working directory (the user's project, maybe a\n// cloned repository) before PATH, as does a relative PATH entry elsewhere: run it from the home folder\n// with only absolute PATH entries, as connect/launch.mjs does for npx.\nconst curlEnv = { ...process.env }\nfor (const key of Object.keys(curlEnv).filter((k) => k.toUpperCase() === \"PATH\")) {\n curlEnv[key] = curlEnv[key].split(path.delimiter).filter((p) => path.isAbsolute(p)).join(path.delimiter)\n}\n\nfunction probeRealtime(protocol) {\n try {\n const out = execFileSync(\"curl\", [\"-sS\", \"-N\", protocol, \"--max-time\", REALTIME_PROBE_SECONDS, \"-H\", \"Accept: text/event-stream\", `${base}/api/realtime`], {\n cwd: homedir(),\n env: curlEnv,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n return out.includes(\"PB_CONNECT\") ? \"ok\" : \"no-event\"\n } catch (error) {\n if (error.code === \"ENOENT\") return \"no-curl\"\n return String(error.stdout ?? \"\").includes(\"PB_CONNECT\") ? \"ok\" : \"no-event\"\n }\n}\n\nconst http2 = probeRealtime(\"--http2\")\nif (http2 === \"no-curl\") {\n warn(\"curl is not installed, so realtime was not checked; open the site in two tabs and check a change appears in both\")\n} else {\n http2 === \"ok\" ? pass(\"realtime connects over HTTP/2 (browsers)\") : bad(\"realtime does not connect over HTTP/2; see troubleshooting.md\")\n probeRealtime(\"--http1.1\") === \"ok\"\n ? pass(\"realtime connects over HTTP/1.1 (Node.js clients, dev proxies)\")\n : warn(\"realtime does not connect over HTTP/1.1: browsers are fine, Node.js subscribers need the workaround in troubleshooting.md\")\n}\n\nconst dashboard = await fetch(`${base}/_/`, { signal: AbortSignal.timeout(PAGE_TIMEOUT_MS) }).catch(() => null)\ndashboard?.status === 200 ? pass(`dashboard is at ${base}/_/`) : bad(`dashboard returned ${dashboard?.status ?? \"no response\"}`)\n\nconst home = await fetch(`${base}/`, { signal: AbortSignal.timeout(PAGE_TIMEOUT_MS) }).catch(() => null)\nconst homeText = home ? await home.text() : \"\"\nif (!home || home.status >= 400) bad(`the website itself returned ${home?.status ?? \"no response\"}; deploy the frontend`)\nelse if (/<title>\\s*Coming soon\\s*<\\/title>/i.test(homeText)) {\n warn(\"the website still shows Hostinger's placeholder page; deploy the frontend\")\n} else pass(\"the website is serving the app\")\n\nfinish()\n\nfunction finish() {\n console.log(`\\n${failures ? \"NOT READY\" : \"READY\"}: ${failures} failed, ${warnings} warnings`)\n process.exit(failures ? 1 : 0)\n}\n"
|
|
295
295
|
},
|
|
296
296
|
{
|
|
297
297
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/troubleshooting.md",
|
|
@@ -358,10 +358,10 @@ export default [
|
|
|
358
358
|
},
|
|
359
359
|
{
|
|
360
360
|
"uri": "skill://hostinger-headless/steps/06-frontend/SKILL.md",
|
|
361
|
-
"digest": "sha256:
|
|
362
|
-
"size":
|
|
361
|
+
"digest": "sha256:310321cd6787ac255d41f662ffed5d5aee9a4b520654893efb0e22b2f9396010",
|
|
362
|
+
"size": 12069,
|
|
363
363
|
"mimeType": "text/markdown",
|
|
364
|
-
"text": "---\nname: headless-step-frontend\ndescription: \"Step 6 (frontend) of the Hostinger Headless flow. Builds the website that renders the backend's content. Figures out (or confirms) the framework — defaulting to Next.js SSR — implements the look already chosen in design.md (the design step's contract), and builds the source into src/. Only ask for the clarifications you actually need.\"\n---\n\n# headless-step-frontend\n\nBuild the site's frontend against the backend from `site.json`, implementing the look the design step\nalready chose and wrote to **`design.md`** (plus the logo in `brand/`). The design is decided; this step\nis where it becomes real code. There's no per-framework recipe — use good judgement, follow `design.md`\nas the contract, and ask only for the clarifications you genuinely need. **Out:** source in the site\nworkspace `~/.hostinger/<domain>/src/`.\n\n> **Build mode \"Bring your own frontend\"? Read this first (any backend).** Read `brief.md` → **Build mode**.\n> When it is **Bring your own frontend**, follow [`bring-your-own-frontend.md`](bring-your-own-frontend.md): wire the user's own project to the\n> backend instead of scaffolding one. When it is **Agent designs and builds**, proceed normally.\n\n> **PocketBase backend?** A `pocketbase` brief has **no CMS/store**: the app's data lives in the\n> PocketBase backend recorded in `site.json → pocketbase`, its collections in `pocketbase/schema.json`\n> (and the `## Data` section of `content-model.md`), and its fixed copy in `content-model.md`. A new\n> app is scaffolded from `brief.md` and `design.md` and binds its forms and views to the collections\n> in `pocketbase/schema.json`; an existing app under **Agent designs and builds** starts from its\n> source, keeps its screens and features, wires its data to the backend and rebuilds its UI to\n> `design.md`. In Step 3 follow the PocketBase bullet.\n\n## Step 1 — Pick the framework (guess → default → confirm)\n\n**The rendering is already decided in `brief.md` → Rendering** (SSR or SSG, set during refine). Honour\nit, and the backend constraint:\n\n- **Ecommerce → SSR required** (carts/search need per-request rendering). Any SSR framework works —\n Next.js is the default, not a requirement (Express, Nuxt, SvelteKit, etc. are all fine).\n- **WordPress + WooCommerce → SSR required** (same reason — cart/checkout need per-request rendering).\n- **WordPress → SSG (Astro)** when the brief says SSG, otherwise **SSR (Next.js default)**.\n- **PocketBase → the app's own stack.** An **existing app** keeps its current framework (don't impose one), including\n one rebuilt under **Agent designs and builds**; a\n **new app** uses whatever fits the brief (SSR or SPA). Either way it deploys as a Node.js app (Step 8) —\n an SSR app runs a server, a SPA builds to static output. The app must not serve anything under\n `/api` or `/_`: PocketBase owns those paths on this domain, so server routes go under another prefix\n (`/server`): Next.js `app/server/…` never `app/api/…`, and likewise no Nuxt `server/api/`, SvelteKit\n `src/routes/api/` or Astro `src/pages/api/`.\n- Map rendering → framework: **`ssr` → Next.js**, **`ssg` → Astro** — unless the brief/prompt explicitly\n names another supported framework, in which case use that.\n\nSupported frameworks are the ones in deploy's *Build configurations* table (`../08-deploy/SKILL.md`).\n\nConfirm the framework with the user in one line only if the brief left it open. Record the choice in\n`state.json`:\n\n```json\n{ \"frontend\": { \"framework\": \"nextjs\", \"rendering\": \"ssr\" } }\n```\n\nIf the brief is silent, default to **Next.js SSR**.\n\n## Step 2 — Implement `design.md` (don't re-design)\n\nThe look was already chosen and written by the design step. **Read `~/.hostinger/<domain>/design.md` and\nimplement it faithfully** — tokens (colour, type, spacing), components, per-page composition, imagery and\naccessibility — plus the logo files in `brand/`. Don't re-run design questions or invent a new direction here.\n\n- Treat `design.md` as the contract: the built pages should match its tokens, type scale, components and\n per-page composition, and the 8-point grid / WCAG 2.2 AA rules it carries.\n- Build the **logo** and favicon exactly as `design.md` → **Logo** → *Use* says; never recolour or redraw\n what is in `brand/`.\n- If `design.md` is **missing** (e.g. a resumed older build), fall back to `brief.md → Design direction`\n (reference site, colours, brand, adjectives) and a tasteful, accessible default — but prefer `design.md`\n whenever it exists.\n- **Don't gate on approval here** — the result is shown at **validate** (Step 7).\n\n**Only ask about the code, and only if it matters** (design decisions belong in the design step):\n- Where the **source should live** — default `~/.hostinger/<domain>/src/`; ask only if they want a\n specific folder or an existing repo.\n- **Git** — initialise / connect / push (default: a local project, no remote).\n- A specific **component library** or technical must-have, if they implied one.\n\n## Step 3 — Build against the backend\n\nTwo phases around the instance barrier (see the top-level `SKILL.md`): scaffold + build the shell while\nprovision settles, then wire live data once `provision.status == \"completed\"`.\n\nRead the backend from `site.json`:\n\n- **WordPress** → `urls.rest_api` (`wp/v2`), public read. Content is in the posts/pages/categories/media\n the content-model push created; nav/plan come from `content-model.md`. Map each item's **SEO** from its\n `yoast_head_json` into the page `<head>` (title, description, Open Graph, JSON-LD schema) — Yoast is\n installed by default at provision (`site.json → seo.enabled: true`). If `seo.enabled` is `false`\n (Yoast absent), fall back to generating per-page title/description/OG tags from each item's content.\n - **Decode WordPress text.** WordPress returns titles and names HTML-encoded (`Tea & Cake`,\n `don’t`). Add the `entities` package and, in the one data module, run every title, name\n and SEO field you render as plain text (posts, pages, terms, Yoast, Store API products and\n categories) through `decodeHTML` once; strip an excerpt's tags first if you show it as text.\n Leave HTML fields (`content.rendered`, an excerpt shown as HTML) as they are, and never inject a\n decoded field as raw HTML.\n - **Contact form** (`site.json → contact_form.enabled: true`, any WordPress backend) → render the\n contact page's form and submit it **client-side** to `contact_form.feedback_url` exactly as\n [`../04-content-model/wordpress/contact-form.md`](../04-content-model/wordpress/contact-form.md) §3\n says. When `contact_form.enabled` is `false` or absent, render the contact page with plain contact\n details and **no form** — graceful, like disabled checkout; never half-build.\n- **WordPress + WooCommerce** (`site.json → woocommerce.enabled: true`) → the WordPress bullet above **plus**\n the store, read over the **public WooCommerce Store API** (`site.json → urls.store_api`): follow\n [`../04-content-model/wordpress/woocommerce.md`](../04-content-model/wordpress/woocommerce.md) §2 for\n the calls, headers and minor-unit prices, and §4 for `site.json → woocommerce.payment_enabled` (while\n `false`, a graceful disabled-checkout state, no `/checkout` call, not a build error). **Never embed a\n consumer key client-side.**\n- **Ecommerce** → the public Hostinger Storefront Core V2 API: follow [`ecommerce.md`](ecommerce.md).\n- **PocketBase** → the `pocketbase` SDK against the backend on the same domain, following\n [`../04-content-model/pocketbase/frontend.md`](../04-content-model/pocketbase/frontend.md) (skip its\n static `.htaccess` section: a headless site deploys as Node.js and keeps no `.htaccess`). In the one\n data module: `new PocketBase(<origin>)` where the origin is `window.location.origin` in the browser\n and `site.json → urls.site` in local dev and on the server, then `pb.autoCancellation(false)` once.\n Build filters with `pb.filter()`, load a list then subscribe to it for live views, and unsubscribe on\n unmount. Build each form and view against the fields in `pocketbase/schema.json`, and show a rule\n rejection (a 400 with no field errors, a 404 on update) as a normal \"not allowed\" state. Add the\n sign-in form only when the schema has an auth collection visitors use\n ([`../04-content-model/pocketbase/auth.md`](../04-content-model/pocketbase/auth.md)). A public form\n includes its recipe's honeypot field, empty and hidden. **The superuser password never reaches the\n frontend**; server-side superuser work reads `PB_URL`, `PB_SUPERUSER_EMAIL` and\n `PB_SUPERUSER_PASSWORD` from the app's environment variables (`frontend.md`, Node.js apps). For an\n existing app, keep its screens and swap its data calls to the backend.\n\nGuidelines (framework-agnostic):\n\n- **One data module** is the single place that talks to the backend (e.g. `src/lib/data.ts`) — one file\n to inspect, one base URL to switch. Keep it swappable so the shell can build against stubs first.\n- **Fetch at request time for SSR** (fresh content, no rebuild); a static build fetches at build time.\n- **A failed or incomplete fetch is an error, not a silent empty/placeholder.** Planned content missing\n from the API is a build error too — a site that builds with holes ships with holes. *(On PocketBase\n the planned content is the fixed pages plus the seed records.)*\n- **`content-model.md` is the source for what should exist** (pages, nav, collections mapping) — on\n every backend; on PocketBase it also carries the `## Data` section.\n- **No `.htaccess`** in the project (deploy would overwrite the live one); don't commit `node_modules`\n or build output.\n- Set `engines.node` to `22` (the deploy builds on Node 22).\n- **Next.js 16+ only:** set the `build` script to `next build --webpack`, not plain `next build`. Next.js\n 16 defaults `next build` to **Turbopack**, whose native compiler needs a newer glibc than the Hostinger\n build server has, so a Turbopack build fails on deploy and won't fall back to webpack. Webpack builds\n clean there. The `--webpack` flag exists only on Next.js 16+; on **Next.js 15.x** leave the build script\n as plain `next build` (it already defaults to webpack). (Alternative: pin Next.js to `15.x`, keeping\n plain `next build`.)\n\n## Step 4 — Hand off\n\nConfirm the project builds clean locally against the live backend, looks right at desktop and phone\nwidth (below), no placeholder/fixture content remains, and `state.json → frontend` matches what you\nbuilt. Update `state.json` (`stage: \"validate\"`).\nValidate (Step 7) owns the clean rebuild + user preview; deploy (Step 8) ships it with the `app_type`\nand output directory that match the chosen framework + rendering.\n\n**Visual check.** With the site running locally against the live backend, look at the home page and one\npage of each template (e.g. a post, a product, the contact page) at desktop and phone width. Take all the\nscreenshots first, then open them all in one turn where your tool can open several images at once, since\neach separate look costs a model turn. Don't tile several pages onto one image or take one tall\nfull-page shot: the viewer shrinks big images, and a shrunk page hides small bugs like a wrapped line.\nAfter a fix, re-shoot only what changed. Phone width is where most layout bugs show. Headless Chrome\nwon't size a window below ~500 px, so a phone-width window comes back cropped: set a 390 px viewport\n(e.g. Playwright), or put one route in 1280 px and 390 px iframes side by side on a local page to get\nboth widths in one image. The live site runs this same build, so it needs no screenshots; deploy checks\nthat it serves.\n\n> **PocketBase:** the app reaches the live backend from local dev (`frontend.md`, Local development),\n> so check one list and one create against it here, then delete the test records before handing over.\n"
|
|
364
|
+
"text": "---\nname: headless-step-frontend\ndescription: \"Step 6 (frontend) of the Hostinger Headless flow. Builds the website that renders the backend's content. Figures out (or confirms) the framework — defaulting to Next.js SSR — implements the look already chosen in design.md (the design step's contract), and builds the source into src/. Only ask for the clarifications you actually need.\"\n---\n\n# headless-step-frontend\n\nBuild the site's frontend against the backend from `site.json`, implementing the look the design step\nalready chose and wrote to **`design.md`** (plus the logo in `brand/`). The design is decided; this step\nis where it becomes real code. There's no per-framework recipe — use good judgement, follow `design.md`\nas the contract, and ask only for the clarifications you genuinely need. **Out:** source in the site\nworkspace `~/.hostinger/<domain>/src/`.\n\n> **Build mode \"Bring your own frontend\"? Read this first (any backend).** Read `brief.md` → **Build mode**.\n> When it is **Bring your own frontend**, follow [`bring-your-own-frontend.md`](bring-your-own-frontend.md): wire the user's own project to the\n> backend instead of scaffolding one. When it is **Agent designs and builds**, proceed normally.\n\n> **PocketBase backend?** A `pocketbase` brief has **no CMS/store**: the app's data lives in the\n> PocketBase backend recorded in `site.json → pocketbase`, its collections in `pocketbase/schema.json`\n> (and the `## Data` section of `content-model.md`), and its fixed copy in `content-model.md`. A new\n> app is scaffolded from `brief.md` and `design.md` and binds its forms and views to the collections\n> in `pocketbase/schema.json`; an existing app under **Agent designs and builds** starts from its\n> source, keeps its screens and features, wires its data to the backend and rebuilds its UI to\n> `design.md`. In Step 3 follow the PocketBase bullet.\n\n## Step 1 — Pick the framework (guess → default → confirm)\n\n**The rendering is already decided in `brief.md` → Rendering** (SSR or SSG, set during refine). Honour\nit, and the backend constraint:\n\n- **Ecommerce → SSR required** (carts/search need per-request rendering). Any SSR framework works —\n Next.js is the default, not a requirement (Express, Nuxt, SvelteKit, etc. are all fine).\n- **WordPress + WooCommerce → SSR required** (same reason — cart/checkout need per-request rendering).\n- **WordPress → SSG (Astro)** when the brief says SSG, otherwise **SSR (Next.js default)**.\n- **PocketBase → the app's own stack.** An **existing app** keeps its current framework (don't impose one), including\n one rebuilt under **Agent designs and builds**; a\n **new app** uses whatever fits the brief (SSR or SPA). Either way it deploys as a Node.js app (Step 8) —\n an SSR app runs a server, a SPA builds to static output. The app must not serve anything under\n `/api` or `/_`: PocketBase owns those paths on this domain, so server routes go under another prefix\n (`/server`): Next.js `app/server/…` never `app/api/…`, and likewise no Nuxt `server/api/`, SvelteKit\n `src/routes/api/` or Astro `src/pages/api/`.\n- Map rendering → framework: **`ssr` → Next.js**, **`ssg` → Astro** — unless the brief/prompt explicitly\n names another supported framework, in which case use that.\n\nSupported frameworks are the ones in deploy's *Build configurations* table (`../08-deploy/SKILL.md`).\n\nConfirm the framework with the user in one line only if the brief left it open. Record the choice in\n`state.json`:\n\n```json\n{ \"frontend\": { \"framework\": \"nextjs\", \"rendering\": \"ssr\" } }\n```\n\nIf the brief is silent, default to **Next.js SSR**.\n\n## Step 2 — Implement `design.md` (don't re-design)\n\nThe look was already chosen and written by the design step. **Read `~/.hostinger/<domain>/design.md` and\nimplement it faithfully** — tokens (colour, type, spacing), components, per-page composition, imagery and\naccessibility — plus the logo files in `brand/`. Don't re-run design questions or invent a new direction here.\n\n- Treat `design.md` as the contract: the built pages should match its tokens, type scale, components and\n per-page composition, and the 8-point grid / WCAG 2.2 AA rules it carries.\n- Build the **logo** and favicon exactly as `design.md` → **Logo** → *Use* says; never recolour or redraw\n what is in `brand/`.\n- If `design.md` is **missing** (e.g. a resumed older build), fall back to `brief.md → Design direction`\n (reference site, colours, brand, adjectives) and a tasteful, accessible default — but prefer `design.md`\n whenever it exists.\n- **Don't gate on approval here** — the result is shown at **validate** (Step 7).\n\n**Only ask about the code, and only if it matters** (design decisions belong in the design step):\n- Where the **source should live** — default `~/.hostinger/<domain>/src/`; ask only if they want a\n specific folder or an existing repo.\n- **Git** — initialise / connect / push (default: a local project, no remote).\n- A specific **component library** or technical must-have, if they implied one.\n\n## Step 3 — Build against the backend\n\nTwo phases around the instance barrier (see the top-level `SKILL.md`): scaffold + build the shell while\nprovision settles, then wire live data once `provision.status == \"completed\"`.\n\nRead the backend from `site.json`:\n\n- **WordPress** → `urls.rest_api` (`wp/v2`), public read. Content is in the posts/pages/categories/media\n the content-model push created; nav/plan come from `content-model.md`. Map each item's **SEO** from its\n `yoast_head_json` into the page `<head>` (title, description, Open Graph, JSON-LD schema) — Yoast is\n installed by default at provision (`site.json → seo.enabled: true`). If `seo.enabled` is `false`\n (Yoast absent), fall back to generating per-page title/description/OG tags from each item's content.\n - **Decode WordPress text.** WordPress returns titles and names HTML-encoded (`Tea & Cake`,\n `don’t`). Add the `entities` package and, in the one data module, run every title, name\n and SEO field you render as plain text (posts, pages, terms, Yoast, Store API products and\n categories) through `decodeHTML` once; strip an excerpt's tags first if you show it as text.\n Leave HTML fields (`content.rendered`, an excerpt shown as HTML) as they are, and never inject a\n decoded field as raw HTML.\n - **Contact form** (`site.json → contact_form.enabled: true`, any WordPress backend) → render the\n contact page's form and submit it **client-side** to `contact_form.feedback_url` exactly as\n [`../04-content-model/wordpress/contact-form.md`](../04-content-model/wordpress/contact-form.md) §3\n says. When `contact_form.enabled` is `false` or absent, render the contact page with plain contact\n details and **no form** — graceful, like disabled checkout; never half-build.\n- **WordPress + WooCommerce** (`site.json → woocommerce.enabled: true`) → the WordPress bullet above **plus**\n the store, read over the **public WooCommerce Store API** (`site.json → urls.store_api`): follow\n [`../04-content-model/wordpress/woocommerce.md`](../04-content-model/wordpress/woocommerce.md) §2 for\n the calls, headers and minor-unit prices, and §4 for `site.json → woocommerce.payment_enabled` (while\n `false`, a graceful disabled-checkout state, no `/checkout` call, not a build error). **Never embed a\n consumer key client-side.**\n- **Ecommerce** → the public Hostinger Storefront Core V2 API: follow [`ecommerce.md`](ecommerce.md).\n- **PocketBase** → the `pocketbase` SDK against the backend on the same domain, following\n [`../04-content-model/pocketbase/frontend.md`](../04-content-model/pocketbase/frontend.md) (skip its\n static `.htaccess` section: a headless site deploys as Node.js and keeps no `.htaccess`). In the one\n data module: `new PocketBase(<origin>)` where the origin is `window.location.origin` in the browser\n and `site.json → urls.site` in local dev and on the server, then `pb.autoCancellation(false)` once.\n Build filters with `pb.filter()`, load a list then subscribe to it for live views, and unsubscribe on\n unmount. Build each form and view against the fields in `pocketbase/schema.json`, and show a rule\n rejection (a 400 with no field errors, a 404 on update) as a normal \"not allowed\" state. Add the\n sign-in form only when the schema has an auth collection visitors use\n ([`../04-content-model/pocketbase/auth.md`](../04-content-model/pocketbase/auth.md)). A public form\n includes its recipe's honeypot field, empty and hidden. **The superuser password never reaches the\n frontend**; server-side superuser work reads `PB_URL`, `PB_SUPERUSER_EMAIL` and\n `PB_SUPERUSER_PASSWORD` from the app's environment variables and signs in **its own** server-only\n client, never the shared `pb` that renders pages for visitors (`frontend.md`, Node.js apps). For an\n existing app, keep its screens and swap its data calls to the backend.\n\nGuidelines (framework-agnostic):\n\n- **One data module** is the single place that talks to the backend (e.g. `src/lib/data.ts`) — one file\n to inspect, one base URL to switch. Keep it swappable so the shell can build against stubs first.\n- **Fetch at request time for SSR** (fresh content, no rebuild); a static build fetches at build time.\n- **A failed or incomplete fetch is an error, not a silent empty/placeholder.** Planned content missing\n from the API is a build error too — a site that builds with holes ships with holes. *(On PocketBase\n the planned content is the fixed pages plus the seed records.)*\n- **`content-model.md` is the source for what should exist** (pages, nav, collections mapping) — on\n every backend; on PocketBase it also carries the `## Data` section.\n- **No `.htaccess`** in the project (deploy would overwrite the live one); don't commit `node_modules`\n or build output.\n- Set `engines.node` to `22` (the deploy builds on Node 22).\n- **Next.js 16+ only:** set the `build` script to `next build --webpack`, not plain `next build`. Next.js\n 16 defaults `next build` to **Turbopack**, whose native compiler needs a newer glibc than the Hostinger\n build server has, so a Turbopack build fails on deploy and won't fall back to webpack. Webpack builds\n clean there. The `--webpack` flag exists only on Next.js 16+; on **Next.js 15.x** leave the build script\n as plain `next build` (it already defaults to webpack). (Alternative: pin Next.js to `15.x`, keeping\n plain `next build`.)\n\n## Step 4 — Hand off\n\nConfirm the project builds clean locally against the live backend, looks right at desktop and phone\nwidth (below), no placeholder/fixture content remains, and `state.json → frontend` matches what you\nbuilt. Update `state.json` (`stage: \"validate\"`).\nValidate (Step 7) owns the clean rebuild + user preview; deploy (Step 8) ships it with the `app_type`\nand output directory that match the chosen framework + rendering.\n\n**Visual check.** With the site running locally against the live backend, look at the home page and one\npage of each template (e.g. a post, a product, the contact page) at desktop and phone width. Take all the\nscreenshots first, then open them all in one turn where your tool can open several images at once, since\neach separate look costs a model turn. Don't tile several pages onto one image or take one tall\nfull-page shot: the viewer shrinks big images, and a shrunk page hides small bugs like a wrapped line.\nAfter a fix, re-shoot only what changed. Phone width is where most layout bugs show. Headless Chrome\nwon't size a window below ~500 px, so a phone-width window comes back cropped: set a 390 px viewport\n(e.g. Playwright), or put one route in 1280 px and 390 px iframes side by side on a local page to get\nboth widths in one image. The live site runs this same build, so it needs no screenshots; deploy checks\nthat it serves.\n\n> **PocketBase:** the app reaches the live backend from local dev (`frontend.md`, Local development),\n> so check one list and one create against it here, then delete the test records before handing over.\n"
|
|
365
365
|
},
|
|
366
366
|
{
|
|
367
367
|
"uri": "skill://hostinger-headless/steps/06-frontend/bring-your-own-frontend.md",
|
package/src/core/skills.ts
CHANGED
|
@@ -204,10 +204,10 @@ const skills: Skill[] = [
|
|
|
204
204
|
},
|
|
205
205
|
{
|
|
206
206
|
"uri": "skill://hostinger-headless/steps/03-provision/pocketbase/SKILL.md",
|
|
207
|
-
"digest": "sha256:
|
|
208
|
-
"size":
|
|
207
|
+
"digest": "sha256:a6c10a6378a365aef891ad00701efc731f94a4e7e7fa4647e5776561f91d280c",
|
|
208
|
+
"size": 12783,
|
|
209
209
|
"mimeType": "text/markdown",
|
|
210
|
-
"text": "---\nname: headless-step-provision-pocketbase\ndescription: \"Provision the PocketBase backend for the Hostinger Headless flow: create a headless website (type headless_pocketbase) or adopt the one onboarding made, then create its PocketBase backend with hosting_pocketbase_create-backend (database, visitor sign-in, file storage and realtime at /api, the owner's dashboard at /_/), save the one-time superuser password outside the deployable source, verify it answers, and record it in site.json. For any app, SPA or site whose visitors create its data.\"\n---\n\n# headless-step-provision-pocketbase\n\nProvision a **headless website with a PocketBase backend** for `<domain>` and prove it is ready. This\nis the backend for **any app, SPA or site whose visitors create the data it keeps** — accounts,\nbookings, comments, votes, scores, order requests, uploads, live messages. There is no CMS and no store\nengine here. PocketBase runs on the site's own domain: the REST and realtime API at\n`https://<domain>/api`, the owner's dashboard at `https://<domain>/_/`. Every other path is the\nfrontend that the frontend step builds and the deploy step ships as a Node.js application.\n**Out:** `site.json` and `~/.hostinger/<domain>/.pocketbase/credentials.json`.\n\n> **Not WordPress, not Ecommerce.** Never provision `headless_wordpress` / `headless_ecommerce` for a\n> PocketBase build, and never install WordPress at `/cms`: Hostinger refuses a PocketBase backend on a\n> headless WordPress site. The app owns every route except `/api` and `/_`.\n\nAll website operations below go through the Hostinger connector (`execute`). Read each operation's\n`inputSchema` (from `search`) before its first call.\n\n> **Fire vs join (background provision).** For a **fresh site**, the fire half is Step 2's\n> `hosting_websites_create`; the join half is `wait.mjs setup`, then Step 3 (the backend), Step 4 and\n> Step 5. For an **adopted shell** (onboarding's `headless_empty` or `headless_pocketbase` site), the\n> fire half is Step 3's `hosting_pocketbase_create-backend` call plus saving its response — one call\n> that returns at once — and the join half is `wait.mjs pocketbase`, Step 4 and Step 5. Record\n> `provision.in_progress` after the fire and return to the prepare work (see the router `../SKILL.md`);\n> join when an instance-barrier step needs the backend, or immediately if the agent can't interleave.\n> A site whose backend Step 1 already finds means provision is done: record `provision.completed` and\n> adopt it.\n\n## Step 0 — Preflight\n\n`search` with the query `pocketbase`. You need `hosting_pocketbase_create-backend`,\n`hosting_pocketbase_backend` and `hosting_pocketbase_set-superuser`; read each one's `inputSchema`\nbefore its first call. If any is missing, the connector is outdated: update it (connect's Phase 1\ninstall), log an `issue` event and stop. **Never improvise a database in its place.**\n\n## Step 1 — Detect before you create (never provision twice)\n\nRun these in order: the kind checks (points 1–3) decide whether this site may be used at all, before\nits setup status (point 4) says where to pick it up.\n\n1. `hosting_websites_list { \"domain\": \"<domain>\" }` — substring filter, so **exact-match** the row's\n `domain`. If a row exists, note `username`, `order_id`, `website_type`. No exact row → nothing\n exists on this domain → **create fresh** (Step 2).\n2. **A row of another kind** (`website_type` not `headless`: a WordPress or store site) → stop and\n tell the user — this domain already hosts something else. **Never create a second site.**\n3. **A `headless` row.** `wordpress_installations_list { username, domain, ownership: \"all\" }` with a\n `directory: \"cms\"` row → stop and tell the user: this is a headless WordPress site, and Hostinger\n refuses PocketBase there. Otherwise `hosting_pocketbase_backend { username, domain }`:\n - a backend (any `state` but `missing`) → **adopt it**; Step 3 point 1 settles the credentials\n (rotate the superuser when this build made the backend and the file is gone, otherwise ask).\n - 404, or `state: \"missing\"` → the shell is empty (onboarding's `headless_empty`, or a\n `headless_pocketbase` site whose backend wasn't created yet): **adopt the site, don't call\n `hosting_websites_create`**, and create the backend on it in Step 3 with this row's `username`.\n **Only provision PocketBase for a `pocketbase` brief.** A `wordpress` or `ecommerce` brief belongs\n in those subfolders — never give it a PocketBase backend.\n4. **Where to pick it up.** `hosting_websites_list-setups { \"domain\": \"<domain>\" }` — exact-match the row:\n - `completed`, or no row (it drops off after 24 h) → the website is ready → Step 3.\n - `running` → the setup is still going: at the join, `cd \"$HOME\" && node <skill>/wait.mjs setup <domain>`\n before Step 3.\n - `failed` → tell the user and point them at hPanel; do **not** call `hosting_websites_create` again on your own.\n\n## Step 2 — Create (only when nothing exists)\n\n1. Pick the plan: `hosting_orders_list { \"statuses\": [\"active\"] }`. One active order → use it; several\n → ask the user which.\n2. Start the setup as a **headless website marked for PocketBase** (it installs nothing yet; Step 3\n creates the backend):\n\n ```json\n { \"operation\": \"hosting_websites_create\",\n \"params\": { \"order_id\": <order_id>, \"type\": \"headless_pocketbase\", \"domain\": \"<domain>\" } }\n ```\n\n `domain` must be a **customer-owned** domain. For a temporary `*.hostingersite.com` subdomain,\n **omit `domain`** — the setup generates one itself and returns it in the response. Don't call a\n separate subdomain op to make one first: there's no need in this flow. The response then carries the\n generated domain: if it differs from the workspace directory name, move `~/.hostinger/<old>/` to\n `~/.hostinger/<new>/`\n (if `<new>/` already exists, stop and ask instead of moving into it),\n update the domain in `brief.md`, and tell the user the new domain.\n3. Don't wait here. At the join, `cd \"$HOME\" && node <skill>/wait.mjs setup <domain>` (see *Waiting on Hostinger* in\n the top-level `SKILL.md`) returns once the setup is `completed`, usually at once by then. A `failed`\n setup → stop, point at hPanel. Then Step 3.\n\n## Step 3 — Create the backend\n\nNeeds the website (setup `completed`). On an adopted shell this is the **fire** half; on a fresh site\nit runs at the join.\n\n1. **Already there?** `hosting_pocketbase_backend { username, domain }`. A backend plus\n `~/.hostinger/<domain>/.pocketbase/credentials.json` with a matching `domain` → adopt it and go to\n point 4. A backend without that file → the password is gone (Hostinger returns it once and never\n stores it): when this build made it (a resumed run, `site.json → backend: \"pocketbase\"`), rotate it\n with `hosting_pocketbase_set-superuser { username, domain }` (no password, so a strong one is\n generated) and save the response as in point 2; when it may belong to something else, **ask** first.\n2. **Create it.** `hosting_pocketbase_create-backend { username, domain }` **without**\n `superuser_password`. As soon as the call returns, before any other step or message, write the\n **full response** to `~/.hostinger/<domain>/.pocketbase/credentials.json` with your file-writing\n tool and `chmod 600` it (on Windows the profile folder is already private). It holds `domain`,\n `api_url`, `admin_url`, `superuser_email`, `superuser_password`, `instance_id`, `state` and\n `version`; **the password is returned only this once**. The file sits in the workspace, outside\n `src/`, so no deploy archive can include it. Never print the password or put it in `site.json`,\n `brief.md`, the run log or a chat reply.\n3. **A 422 is not always \"already exists\"**: read its message and show it to the user when you stop.\n - *This website already has a PocketBase instance* → go back to point 1 (once; if it still finds no\n backend, stop and show the user the message).\n - *not supported on headless WordPress websites* or *cannot be added to a parked domain* → stop\n and tell the user: this domain can't take PocketBase.\n - *not available* / *no access yet* (PocketBase is rolling out gradually and this account isn't\n enabled yet) → stop and tell the user PocketBase isn't enabled on their account yet, quoting the\n message; log an `issue` event. **Never improvise a database in its place.**\n - Any other message → stop and show it to the user. Never retry a 422 blindly.\n4. **Wait for it.** `state` may be `null` right after creation; that's normal.\n `cd \"$HOME\" && node <skill>/wait.mjs pocketbase <domain>` returns once `https://<domain>/api/health`\n answers 200 (over `http://` with `https_pending: true` while a new domain's certificate is still\n installing — fine, go on). If it times out, re-read `hosting_pocketbase_backend`: `failed` means\n the last start didn't succeed and Hostinger retries it on its own after `retry_after_seconds`\n (the data is intact — wait that long and read again, never delete the backend); `unregistered`\n means it's broken → stop and show the user; `missing` means its files are gone → point 2 creates\n a new, empty one. The backend sleeps after about 5 idle minutes, so one 503 on a first request is\n a wake-up.\n\nPocketBase owns `/api` and `/_` on this domain; the app's own server routes use another prefix (e.g.\n`/server`). The owner sets outgoing mail (SMTP), backups and social sign-in in the dashboard: they\naren't in the API. `hosting_pocketbase_delete-backend` destroys every record and upload — never call\nit in this flow.\n\n## Step 4 — Verify\n\n| Check | How | Expect |\n|---|---|---|\n| Website exists | `hosting_websites_list` exact row | the row is present, `username` known |\n| Setup finished *(fresh site only)* | `hosting_websites_list-setups` exact row | `status: completed` |\n| Backend healthy | `hosting_pocketbase_backend { username, domain }` | `state` is `asleep`, `starting` or `running` |\n| PocketBase answers | `GET https://<domain>/api/health` and `GET https://<domain>/_/` | 200 and 200 |\n| Credentials saved | `~/.hostinger/<domain>/.pocketbase/credentials.json` | present, mode `600`, `domain` matches |\n\n`GET https://<domain>/` returns the Hostinger default page (or 403) until the frontend is deployed —\nexpected, not a failure. There is **no `/cms`** on this domain; the app itself serves every route but\n`/api` and `/_` once it is deployed (Step 8).\n\nIf a check fails: retry once after ~30 s; if it still fails, stop and point the user at hPanel.\n\n## Step 5 — Record `site.json`\n\n```json\n{\n \"backend\": \"pocketbase\",\n \"website_type\": \"headless\",\n \"order_id\": 1007223428,\n \"username\": \"u…\",\n \"runtime\": \"nodejs\",\n \"pocketbase\": {\n \"instance_id\": \"…\",\n \"version\": \"…\",\n \"superuser_email\": \"…\",\n \"credentials_file\": \".pocketbase/credentials.json\"\n },\n \"urls\": {\n \"site\": \"https://<domain>\",\n \"api\": \"https://<domain>/api\",\n \"admin\": \"https://<domain>/_/\"\n },\n \"provisioned_at\": \"…\",\n \"verified_at\": \"…\"\n}\n```\n\n`credentials_file` is relative to the workspace `~/.hostinger/<domain>/`. No passwords or tokens in\n`site.json` — the superuser password lives only in the credentials file. Together, `superuser_email`\nand that file are the owner's **login access** to the dashboard at `urls.admin`; the done step hands\nthem over by name (the email, the file's full path, never the password itself).\n\n## Content model & deploy (what happens next)\n\n- **Content model** runs `../../04-content-model/pocketbase/SKILL.md`: it designs the collections,\n access rules and seed records in `pocketbase/schema.json` during the provision wait, then applies\n and verifies them against this backend at the instance barrier. The shared prepare phase still\n writes the site's fixed copy (title, navigation, pages) to `content-model.md`.\n- **Deploy** is a standard Node.js application deploy, handled by `../../08-deploy/SKILL.md`: it archives\n the **source** (not the build output; exclude `node_modules/`, `.next/`, `dist/`, build output and\n `.git/`), then deploys with `hosting_deploy` (`type: \"nodejs\"`, upload + server-side `npm install` +\n build, one shot) passing the framework's `appType` + `outputDirectory` inline, and polls\n `hosting_get-deployment` until the build completes. Any supported `appType` works (Next.js, Nuxt,\n Express, NestJS, Fastify, Vite/React/Vue SPA, …). `/api` and `/_` keep belonging to PocketBase; deploy\n checks they survived.\n"
|
|
210
|
+
"text": "---\nname: headless-step-provision-pocketbase\ndescription: \"Provision the PocketBase backend for the Hostinger Headless flow: create a headless website (type headless_pocketbase) or adopt the one onboarding made, then create its PocketBase backend with hosting_pocketbase_create-backend (database, visitor sign-in, file storage and realtime at /api, the owner's dashboard at /_/), save the one-time superuser password outside the deployable source, verify it answers, and record it in site.json. For any app, SPA or site whose visitors create its data.\"\n---\n\n# headless-step-provision-pocketbase\n\nProvision a **headless website with a PocketBase backend** for `<domain>` and prove it is ready. This\nis the backend for **any app, SPA or site whose visitors create the data it keeps** — accounts,\nbookings, comments, votes, scores, order requests, uploads, live messages. There is no CMS and no store\nengine here. PocketBase runs on the site's own domain: the REST and realtime API at\n`https://<domain>/api`, the owner's dashboard at `https://<domain>/_/`. Every other path is the\nfrontend that the frontend step builds and the deploy step ships as a Node.js application.\n**Out:** `site.json` and `~/.hostinger/<domain>/.pocketbase/credentials.json`.\n\n> **Not WordPress, not Ecommerce.** Never provision `headless_wordpress` / `headless_ecommerce` for a\n> PocketBase build, and never install WordPress at `/cms`: Hostinger refuses a PocketBase backend on a\n> headless WordPress site. The app owns every route except `/api` and `/_`.\n\nAll website operations below go through the Hostinger connector (`execute`). Read each operation's\n`inputSchema` (from `search`) before its first call.\n\n> **Fire vs join (background provision).** For a **fresh site**, the fire half is Step 2's\n> `hosting_websites_create`; the join half is `wait.mjs setup`, then Step 3 (the backend), Step 4 and\n> Step 5. For an **adopted shell** (onboarding's `headless_empty` or `headless_pocketbase` site), the\n> fire half is Step 3's `hosting_pocketbase_create-backend` call plus saving its response — one call\n> that returns at once — and the join half is `wait.mjs pocketbase`, Step 4 and Step 5. Record\n> `provision.in_progress` after the fire and return to the prepare work (see the router `../SKILL.md`);\n> join when an instance-barrier step needs the backend, or immediately if the agent can't interleave.\n> A site whose backend Step 1 already finds means provision is done: record `provision.completed` and\n> adopt it.\n\n## Step 0 — Preflight\n\n`search` with the query `pocketbase`. You need `hosting_pocketbase_create-backend`,\n`hosting_pocketbase_backend` and `hosting_pocketbase_set-superuser`; read each one's `inputSchema`\nbefore its first call. If any is missing, the connector is outdated: update it (connect's Phase 1\ninstall), log an `issue` event and stop. **Never improvise a database in its place.**\n\n## Step 1 — Detect before you create (never provision twice)\n\nRun these in order: the kind checks (points 1–3) decide whether this site may be used at all, before\nits setup status (point 4) says where to pick it up.\n\n1. `hosting_websites_list { \"domain\": \"<domain>\" }` — substring filter, so **exact-match** the row's\n `domain`. If a row exists, note `username`, `order_id`, `website_type`. No exact row → nothing\n exists on this domain → **create fresh** (Step 2).\n2. **A row of another kind** (`website_type` not `headless`: a WordPress or store site) → stop and\n tell the user — this domain already hosts something else. **Never create a second site.**\n3. **A `headless` row.** `wordpress_installations_list { username, domain, ownership: \"all\" }` with a\n `directory: \"cms\"` row → stop and tell the user: this is a headless WordPress site, and Hostinger\n refuses PocketBase there. Otherwise `hosting_pocketbase_backend { username, domain }`:\n - a backend (any `state` but `missing`) → **adopt it**; Step 3 point 1 settles the credentials\n (rotate the superuser when this build made the backend and the file is gone, otherwise ask).\n - 404, or `state: \"missing\"` → the shell is empty (onboarding's `headless_empty`, or a\n `headless_pocketbase` site whose backend wasn't created yet): **adopt the site, don't call\n `hosting_websites_create`**, and create the backend on it in Step 3 with this row's `username`.\n **Only provision PocketBase for a `pocketbase` brief.** A `wordpress` or `ecommerce` brief belongs\n in those subfolders — never give it a PocketBase backend.\n4. **Where to pick it up.** `hosting_websites_list-setups { \"domain\": \"<domain>\" }` — exact-match the row:\n - `completed`, or no row (it drops off after 24 h) → the website is ready → Step 3.\n - `running` → the setup is still going: at the join, `cd \"$HOME\" && node <skill>/wait.mjs setup <domain>`\n before Step 3.\n - `failed` → tell the user and point them at hPanel; do **not** call `hosting_websites_create` again on your own.\n\n## Step 2 — Create (only when nothing exists)\n\n1. Pick the plan: `hosting_orders_list { \"statuses\": [\"active\"] }`. One active order → use it; several\n → ask the user which.\n2. Start the setup as a **headless website marked for PocketBase** (it installs nothing yet; Step 3\n creates the backend):\n\n ```json\n { \"operation\": \"hosting_websites_create\",\n \"params\": { \"order_id\": <order_id>, \"type\": \"headless_pocketbase\", \"domain\": \"<domain>\" } }\n ```\n\n `domain` must be a **customer-owned** domain. For a temporary `*.hostingersite.com` subdomain,\n **omit `domain`** — the setup generates one itself and returns it in the response. Don't call a\n separate subdomain op to make one first: there's no need in this flow. The response then carries the\n generated domain: if it differs from the workspace directory name, move `~/.hostinger/<old>/` to\n `~/.hostinger/<new>/`\n (if `<new>/` already exists, stop and ask instead of moving into it),\n update the domain in `brief.md`, and tell the user the new domain.\n3. Don't wait here. At the join, `cd \"$HOME\" && node <skill>/wait.mjs setup <domain>` (see *Waiting on Hostinger* in\n the top-level `SKILL.md`) returns once the setup is `completed`, usually at once by then. A `failed`\n setup → stop, point at hPanel. Then Step 3.\n\n## Step 3 — Create the backend\n\nNeeds the website (setup `completed`). On an adopted shell this is the **fire** half; on a fresh site\nit runs at the join.\n\n1. **Already there?** `hosting_pocketbase_backend { username, domain }`. A backend plus\n `~/.hostinger/<domain>/.pocketbase/credentials.json` with a matching `domain` → adopt it and go to\n point 4. A backend without that file → the password is gone (Hostinger returns it once and never\n stores it): when this build made it (a resumed run, `site.json → backend: \"pocketbase\"`), rotate it\n with `hosting_pocketbase_set-superuser { username, domain }` (no password, so a strong one is\n generated) and save the response as in point 2; when it may belong to something else, **ask** first.\n2. **Create it.** `hosting_pocketbase_create-backend { username, domain }` **without**\n `superuser_password`. Before the call, make the folder private:\n `mkdir -p ~/.hostinger/<domain>/.pocketbase && chmod 700 ~/.hostinger/<domain>/.pocketbase`, so\n other users of this computer can't read the file even before its own `chmod`. As soon as the call\n returns, before any other step or message, write the\n **full response** to `~/.hostinger/<domain>/.pocketbase/credentials.json` with your file-writing\n tool and `chmod 600` it (on Windows the profile folder is already private). It holds `domain`,\n `api_url`, `admin_url`, `superuser_email`, `superuser_password`, `instance_id`, `state` and\n `version`; **the password is returned only this once**. The file sits in the workspace, outside\n `src/`, so no deploy archive can include it. Never print the password or put it in `site.json`,\n `brief.md`, the run log or a chat reply.\n3. **A 422 is not always \"already exists\"**: read its message and show it to the user when you stop.\n - *This website already has a PocketBase instance* → go back to point 1 (once; if it still finds no\n backend, stop and show the user the message).\n - *not supported on headless WordPress websites* or *cannot be added to a parked domain* → stop\n and tell the user: this domain can't take PocketBase.\n - *not available* / *no access yet* (PocketBase is rolling out gradually and this account isn't\n enabled yet) → stop and tell the user PocketBase isn't enabled on their account yet, quoting the\n message; log an `issue` event. **Never improvise a database in its place.**\n - Any other message → stop and show it to the user. Never retry a 422 blindly.\n4. **Wait for it.** `state` may be `null` right after creation; that's normal.\n `cd \"$HOME\" && node <skill>/wait.mjs pocketbase <domain>` returns once `https://<domain>/api/health`\n answers 200 (over `http://` with `https_pending: true` while a new domain's certificate is still\n installing — fine, go on). If it times out, re-read `hosting_pocketbase_backend`: `failed` means\n the last start didn't succeed and Hostinger retries it on its own after `retry_after_seconds`\n (the data is intact — wait that long and read again, never delete the backend); `unregistered`\n means it's broken → stop and show the user; `missing` means its files are gone → point 2 creates\n a new, empty one. The backend sleeps after about 5 idle minutes, so one 503 on a first request is\n a wake-up.\n\nPocketBase owns `/api` and `/_` on this domain; the app's own server routes use another prefix (e.g.\n`/server`). The owner sets outgoing mail (SMTP), backups and social sign-in in the dashboard: they\naren't in the API. `hosting_pocketbase_delete-backend` destroys every record and upload — never call\nit in this flow.\n\n## Step 4 — Verify\n\n| Check | How | Expect |\n|---|---|---|\n| Website exists | `hosting_websites_list` exact row | the row is present, `username` known |\n| Setup finished *(fresh site only)* | `hosting_websites_list-setups` exact row | `status: completed` |\n| Backend healthy | `hosting_pocketbase_backend { username, domain }` | `state` is `asleep`, `starting` or `running` |\n| PocketBase answers | `GET https://<domain>/api/health` and `GET https://<domain>/_/` | 200 and 200 |\n| Credentials saved | `~/.hostinger/<domain>/.pocketbase/credentials.json` | present, mode `600`, `domain` matches |\n\n`GET https://<domain>/` returns the Hostinger default page (or 403) until the frontend is deployed —\nexpected, not a failure. There is **no `/cms`** on this domain; the app itself serves every route but\n`/api` and `/_` once it is deployed (Step 8).\n\nIf a check fails: retry once after ~30 s; if it still fails, stop and point the user at hPanel.\n\n## Step 5 — Record `site.json`\n\n```json\n{\n \"backend\": \"pocketbase\",\n \"website_type\": \"headless\",\n \"order_id\": 1007223428,\n \"username\": \"u…\",\n \"runtime\": \"nodejs\",\n \"pocketbase\": {\n \"instance_id\": \"…\",\n \"version\": \"…\",\n \"superuser_email\": \"…\",\n \"credentials_file\": \".pocketbase/credentials.json\"\n },\n \"urls\": {\n \"site\": \"https://<domain>\",\n \"api\": \"https://<domain>/api\",\n \"admin\": \"https://<domain>/_/\"\n },\n \"provisioned_at\": \"…\",\n \"verified_at\": \"…\"\n}\n```\n\n`credentials_file` is relative to the workspace `~/.hostinger/<domain>/`. No passwords or tokens in\n`site.json` — the superuser password lives only in the credentials file. Together, `superuser_email`\nand that file are the owner's **login access** to the dashboard at `urls.admin`; the done step hands\nthem over by name (the email, the file's full path, never the password itself).\n\n## Content model & deploy (what happens next)\n\n- **Content model** runs `../../04-content-model/pocketbase/SKILL.md`: it designs the collections,\n access rules and seed records in `pocketbase/schema.json` during the provision wait, then applies\n and verifies them against this backend at the instance barrier. The shared prepare phase still\n writes the site's fixed copy (title, navigation, pages) to `content-model.md`.\n- **Deploy** is a standard Node.js application deploy, handled by `../../08-deploy/SKILL.md`: it archives\n the **source** (not the build output; exclude `node_modules/`, `.next/`, `dist/`, build output and\n `.git/`), then deploys with `hosting_deploy` (`type: \"nodejs\"`, upload + server-side `npm install` +\n build, one shot) passing the framework's `appType` + `outputDirectory` inline, and polls\n `hosting_get-deployment` until the build completes. Any supported `appType` works (Next.js, Nuxt,\n Express, NestJS, Fastify, Vite/React/Vue SPA, …). `/api` and `/_` keep belonging to PocketBase; deploy\n checks they survived.\n"
|
|
211
211
|
},
|
|
212
212
|
{
|
|
213
213
|
"uri": "skill://hostinger-headless/steps/03-provision/wordpress/SKILL.md",
|
|
@@ -253,10 +253,10 @@ const skills: Skill[] = [
|
|
|
253
253
|
},
|
|
254
254
|
{
|
|
255
255
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/frontend.md",
|
|
256
|
-
"digest": "sha256:
|
|
257
|
-
"size":
|
|
256
|
+
"digest": "sha256:d74e777e152651bd16642f2bef3d504f4cd8ddb3fcdf336eef655880d4627d10",
|
|
257
|
+
"size": 6385,
|
|
258
258
|
"mimeType": "text/markdown",
|
|
259
|
-
"text": "# Connecting the app\n\nThe backend is on the same domain as the site, so the browser needs no API URL, no CORS setup and no keys.\n\n## Contents\n\n- Bundled apps, plain HTML, local development\n- Everyday calls, pagination, errors\n- Files\n- Realtime\n- Node.js apps on the same website\n- Routing for single-page apps\n\n## Bundled apps (Vite, React, Vue, Svelte, Next.js static export)\n\n```bash\nnpm install pocketbase@0.28.1\n```\n\n```ts\nimport PocketBase from \"pocketbase\"\n\nexport const pb = new PocketBase(import.meta.env.DEV ? \"https://<domain>\" : window.location.origin)\npb.autoCancellation(false)\n```\n\n`autoCancellation(false)` matters: by default the SDK aborts an earlier request to the same collection when a new one starts, so parallel loads fail with \"The request was aborted\". For Next.js use `process.env.NODE_ENV === \"development\"` in place of `import.meta.env.DEV`.\n\n## Plain HTML\n\n```html\n<script src=\"https://cdn.jsdelivr.net/npm/pocketbase@0.28.1/dist/pocketbase.umd.js\"></script>\n<script>\n const pb = new PocketBase(window.location.origin)\n pb.autoCancellation(false)\n</script>\n```\n\n## Local development\n\nThere is one backend, the live one. In development the app talks to it directly (above), not through a dev-server proxy: a proxy works for REST but realtime through it depends on HTTP/1.1 (`troubleshooting.md`). Records created while testing are real data; delete them in the dashboard before handing over, or use a test account. Opening the app from `file://` does not work for same-origin calls; use the dev server.\n\n## Everyday calls\n\n```ts\nconst page = await pb.collection(\"posts\").getList(1, 20, {\n filter: pb.filter(\"published = {:p} && author = {:a}\", { p: true, a: userId }),\n sort: \"-created\",\n expand: \"author\",\n})\nconst all = await pb.collection(\"products\").getFullList({ sort: \"name\" })\nconst one = await pb.collection(\"posts\").getOne(id)\nconst first = await pb.collection(\"rooms\").getFirstListItem(pb.filter(\"slug = {:s}\", { s: slug }))\nconst post = await pb.collection(\"posts\").create({ title, author: pb.authStore.record.id })\nawait pb.collection(\"posts\").update(post.id, { published: true })\nawait pb.collection(\"posts\").delete(post.id)\n```\n\n- Build every filter with `pb.filter(expr, params)`; never put user input into a filter string yourself.\n- `getList` returns `{ items, page, perPage, totalItems, totalPages }`; `perPage` goes up to 1000. Show \"Load more\" with the next `page`, or pass `skipTotal: true` when the count is not needed (faster).\n- `getFullList` fetches every page; use it only for small collections such as a catalog.\n- `expand: \"author\"` puts the related record in `record.expand.author`, but only if the caller may view it under that collection's rules.\n\n## Errors\n\nErrors are `ClientResponseError` with `status` and `response`:\n\n- 400 with `response.data.<field>.message`: show that message next to the field.\n- 400 \"Failed to create record.\" with empty `data`: the create rule rejected it (honeypot filled, wrong owner, room closed). Show a general \"Could not send\" and check the rule.\n- 404 on view, update or delete: not found or not allowed by the rule.\n- 403: the rule is `null` (superusers only).\n- 429: rate limit. Ask the visitor to wait a minute.\n- `status` 0: network error or aborted request.\n\n## Files\n\n```ts\nconst form = new FormData()\nform.append(\"title\", title)\nform.append(\"cover\", fileInput.files[0])\nconst post = await pb.collection(\"posts\").create(form)\nconst url = pb.files.getURL(post, post.cover, { thumb: \"400x300\" })\n```\n\n- Files over the field's `maxSize` (default 5 MB) are rejected with a field error; check `file.size` before uploading.\n- Thumbnails work only for sizes listed in the field's `thumbs`.\n- For `protected` file fields, fetch a token first: `const token = await pb.files.getToken()` and pass `{ token }` to `getURL`. It expires after a few minutes.\n\n## Realtime\n\n```ts\nconst unsubscribe = await pb.collection(\"messages\").subscribe(\n \"*\",\n (event) => {\n if (event.action === \"create\") add(event.record)\n if (event.action === \"update\") replace(event.record)\n if (event.action === \"delete\") remove(event.record.id)\n },\n { filter: pb.filter(\"room = {:room}\", { room: roomId }), expand: \"author\" },\n)\n```\n\n- Load the initial list first, then subscribe, and merge by `id` so nothing shows twice.\n- Call `unsubscribe()` when the view unmounts.\n- `pb.realtime.isConnected` tells whether the stream is up; show a small \"Live\" or \"Connecting\" indicator.\n- Events follow the collection's view rule: a visitor only receives records they may view.\n- An idle backend sleeps after about 5 minutes and wakes on the next request; an open realtime stream keeps it awake. The first request after sleep can take a few seconds or return 503 once, so retry once and keep timeouts at 10 s or more.\n\n## Node.js apps on the same website\n\nA Node.js app on the site can call its own backend at `https://<domain>` for trusted server-side work (webhooks, scheduled jobs, writes visitors must not make):\n\n1. Store `PB_URL`, `PB_SUPERUSER_EMAIL` and `PB_SUPERUSER_PASSWORD` as Node.js environment variables. `hosting_nodejs_replace-environment-variables` replaces the full set, so read the current ones first and send them all.\n2.
|
|
259
|
+
"text": "# Connecting the app\n\nThe backend is on the same domain as the site, so the browser needs no API URL, no CORS setup and no keys.\n\n## Contents\n\n- Bundled apps, plain HTML, local development\n- Everyday calls, pagination, errors\n- Files\n- Realtime\n- Node.js apps on the same website\n- Routing for single-page apps\n\n## Bundled apps (Vite, React, Vue, Svelte, Next.js static export)\n\n```bash\nnpm install pocketbase@0.28.1\n```\n\n```ts\nimport PocketBase from \"pocketbase\"\n\nexport const pb = new PocketBase(import.meta.env.DEV ? \"https://<domain>\" : window.location.origin)\npb.autoCancellation(false)\n```\n\n`autoCancellation(false)` matters: by default the SDK aborts an earlier request to the same collection when a new one starts, so parallel loads fail with \"The request was aborted\". For Next.js use `process.env.NODE_ENV === \"development\"` in place of `import.meta.env.DEV`.\n\n## Plain HTML\n\n```html\n<script src=\"https://cdn.jsdelivr.net/npm/pocketbase@0.28.1/dist/pocketbase.umd.js\"></script>\n<script>\n const pb = new PocketBase(window.location.origin)\n pb.autoCancellation(false)\n</script>\n```\n\n## Local development\n\nThere is one backend, the live one. In development the app talks to it directly (above), not through a dev-server proxy: a proxy works for REST but realtime through it depends on HTTP/1.1 (`troubleshooting.md`). Records created while testing are real data; delete them in the dashboard before handing over, or use a test account. Opening the app from `file://` does not work for same-origin calls; use the dev server.\n\n## Everyday calls\n\n```ts\nconst page = await pb.collection(\"posts\").getList(1, 20, {\n filter: pb.filter(\"published = {:p} && author = {:a}\", { p: true, a: userId }),\n sort: \"-created\",\n expand: \"author\",\n})\nconst all = await pb.collection(\"products\").getFullList({ sort: \"name\" })\nconst one = await pb.collection(\"posts\").getOne(id)\nconst first = await pb.collection(\"rooms\").getFirstListItem(pb.filter(\"slug = {:s}\", { s: slug }))\nconst post = await pb.collection(\"posts\").create({ title, author: pb.authStore.record.id })\nawait pb.collection(\"posts\").update(post.id, { published: true })\nawait pb.collection(\"posts\").delete(post.id)\n```\n\n- Build every filter with `pb.filter(expr, params)`; never put user input into a filter string yourself.\n- `getList` returns `{ items, page, perPage, totalItems, totalPages }`; `perPage` goes up to 1000. Show \"Load more\" with the next `page`, or pass `skipTotal: true` when the count is not needed (faster).\n- `getFullList` fetches every page; use it only for small collections such as a catalog.\n- `expand: \"author\"` puts the related record in `record.expand.author`, but only if the caller may view it under that collection's rules.\n\n## Errors\n\nErrors are `ClientResponseError` with `status` and `response`:\n\n- 400 with `response.data.<field>.message`: show that message next to the field.\n- 400 \"Failed to create record.\" with empty `data`: the create rule rejected it (honeypot filled, wrong owner, room closed). Show a general \"Could not send\" and check the rule.\n- 404 on view, update or delete: not found or not allowed by the rule.\n- 403: the rule is `null` (superusers only).\n- 429: rate limit. Ask the visitor to wait a minute.\n- `status` 0: network error or aborted request.\n\n## Files\n\n```ts\nconst form = new FormData()\nform.append(\"title\", title)\nform.append(\"cover\", fileInput.files[0])\nconst post = await pb.collection(\"posts\").create(form)\nconst url = pb.files.getURL(post, post.cover, { thumb: \"400x300\" })\n```\n\n- Files over the field's `maxSize` (default 5 MB) are rejected with a field error; check `file.size` before uploading.\n- Thumbnails work only for sizes listed in the field's `thumbs`.\n- For `protected` file fields, fetch a token first: `const token = await pb.files.getToken()` and pass `{ token }` to `getURL`. It expires after a few minutes.\n\n## Realtime\n\n```ts\nconst unsubscribe = await pb.collection(\"messages\").subscribe(\n \"*\",\n (event) => {\n if (event.action === \"create\") add(event.record)\n if (event.action === \"update\") replace(event.record)\n if (event.action === \"delete\") remove(event.record.id)\n },\n { filter: pb.filter(\"room = {:room}\", { room: roomId }), expand: \"author\" },\n)\n```\n\n- Load the initial list first, then subscribe, and merge by `id` so nothing shows twice.\n- Call `unsubscribe()` when the view unmounts.\n- `pb.realtime.isConnected` tells whether the stream is up; show a small \"Live\" or \"Connecting\" indicator.\n- Events follow the collection's view rule: a visitor only receives records they may view.\n- An idle backend sleeps after about 5 minutes and wakes on the next request; an open realtime stream keeps it awake. The first request after sleep can take a few seconds or return 503 once, so retry once and keep timeouts at 10 s or more.\n\n## Node.js apps on the same website\n\nA Node.js app on the site can call its own backend at `https://<domain>` for trusted server-side work (webhooks, scheduled jobs, writes visitors must not make):\n\n1. Store `PB_URL`, `PB_SUPERUSER_EMAIL` and `PB_SUPERUSER_PASSWORD` as Node.js environment variables. `hosting_nodejs_replace-environment-variables` replaces the full set, so read the current ones first and send them all.\n2. Do superuser work on its own client in a server-only module (e.g. `src/lib/pb-admin.ts`), used only by that trusted work: authenticate it once at startup with `admin.collection(\"_superusers\").authWithPassword(email, password)` and again on a 401. Never sign in the shared `pb` client: pages rendered and requests handled for visitors would then run as superuser and skip every collection rule. Server code acting for a visitor uses a client with no superuser sign-in (a new `PocketBase` per request when it carries the visitor's own sign-in).\n3. The app's own routes must not start with `/api` or `/_`; those paths go to PocketBase.\n4. For realtime subscriptions from Node.js, check the HTTP/1.1 note in `troubleshooting.md`.\n\n## Routing for single-page apps\n\nPocketBase owns `/api/*` and `/_/*`. If the app uses history routing (`/rooms/42`) on a static deploy, add `public/.htaccess` so unknown paths load `index.html` without catching the backend:\n\n```apache\nRewriteEngine On\nRewriteCond %{REQUEST_URI} !^/(api|_)(/|$)\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^ /index.html [L]\n```\n\nHash routing (`/#/rooms/42`) needs nothing.\n"
|
|
260
260
|
},
|
|
261
261
|
{
|
|
262
262
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/patterns.md",
|
|
@@ -288,24 +288,24 @@ const skills: Skill[] = [
|
|
|
288
288
|
},
|
|
289
289
|
{
|
|
290
290
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/scripts/pb-apply-schema.mjs",
|
|
291
|
-
"digest": "sha256:
|
|
292
|
-
"size":
|
|
291
|
+
"digest": "sha256:830ed68ca9db9848ac158a6b8976628feefa70d57fcc67d8a5d46d8a438586f5",
|
|
292
|
+
"size": 12542,
|
|
293
293
|
"mimeType": "text/plain",
|
|
294
|
-
"text": "import {\n baseUrlFrom,\n describeError,\n fail,\n listCollections,\n mergeRateLimitRules,\n readCredentials,\n readJson,\n request,\n superuserToken,\n wakeUp,\n} from \"./pb-lib.mjs\"\n\nconst args = process.argv.slice(2)\nconst checkOnly = args.includes(\"--check\")\nconst [schemaPath, credsPath] = args.filter((arg) => arg !== \"--check\")\nif (!schemaPath || (!credsPath && !checkOnly)) {\n fail(\"Usage: node pb-apply-schema.mjs <schema.json> <credentials.json> or node pb-apply-schema.mjs --check <schema.json>\")\n}\n\nconst RULE_KEYS = {\n list: \"listRule\",\n view: \"viewRule\",\n create: \"createRule\",\n update: \"updateRule\",\n delete: \"deleteRule\",\n auth: \"authRule\",\n manage: \"manageRule\",\n}\nconst AUTH_ONLY_RULE_KEYS = new Set([\"auth\", \"manage\"])\nconst COLLECTION_KEYS = new Set([\"name\", \"type\", \"rules\", \"fields\", \"indexes\", \"authOptions\", \"timestamps\", \"viewQuery\", \"seed\"])\nconst COLLECTION_TYPES = new Set([\"base\", \"auth\", \"view\"])\nconst FIELD_TYPES = new Set([\"text\", \"editor\", \"number\", \"bool\", \"email\", \"url\", \"date\", \"autodate\", \"select\", \"file\", \"relation\", \"json\", \"geoPoint\"])\nconst INDEX_NAME = /INDEX\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?[`\"]?(\\w+)[`\"]?/i\nconst TIMESTAMPS = [\n { name: \"created\", type: \"autodate\", onCreate: true, onUpdate: false },\n { name: \"updated\", type: \"autodate\", onCreate: true, onUpdate: true },\n]\n\nconst schema = readJson(schemaPath)\nconst wanted = Array.isArray(schema.collections) ? schema.collections : fail('schema.json needs a top-level \"collections\" array')\nvalidateSchema()\nif (checkOnly) {\n console.log(`OK ${schemaPath} is valid (${wanted.length} collections). Relation targets outside the file are checked when applied.`)\n process.exit(0)\n}\n\nconst creds = readCredentials(credsPath)\nconst base = baseUrlFrom(creds)\nawait wakeUp(base)\nconst token = await superuserToken(base, creds)\n\nconst isView = (collection) => (collection.type ?? \"base\") === \"view\"\nlet collections = await listCollections(base, token)\nawait createMissingCollections(wanted.filter((collection) => !isView(collection)))\ncollections = await listCollections(base, token)\nawait updateFieldsAndIndexes(wanted.filter((collection) => !isView(collection)))\nawait createMissingCollections(wanted.filter(isView))\ncollections = await listCollections(base, token)\nawait updateFieldsAndIndexes(wanted.filter(isView))\nawait applyRules()\nawait applyRateLimits()\nawait seedEmptyCollections()\nconsole.log(`DONE schema applied to ${base}`)\n\nfunction validateSchema() {\n const problems = []\n const names = new Set()\n for (const collection of wanted) {\n const label = collection.name ?? \"(unnamed)\"\n if (!collection.name || !/^[a-z_][a-z0-9_]*$/i.test(collection.name)) problems.push(`invalid collection name \"${collection.name}\"`)\n if (names.has(collection.name)) problems.push(`${label}: listed twice`)\n names.add(collection.name)\n for (const key of Object.keys(collection)) {\n if (!COLLECTION_KEYS.has(key)) problems.push(`${label}: unknown key \"${key}\" (allowed: ${[...COLLECTION_KEYS].join(\", \")})`)\n }\n const type = collection.type ?? \"base\"\n if (!COLLECTION_TYPES.has(type)) problems.push(`${label}: type must be base, auth or view`)\n if (type === \"view\" && !collection.viewQuery) problems.push(`${label}: view collections need \"viewQuery\"`)\n if (type !== \"view\" && collection.viewQuery) problems.push(`${label}: \"viewQuery\" only applies to type \"view\"`)\n for (const key of Object.keys(collection.rules ?? {})) {\n if (!(key in RULE_KEYS)) problems.push(`${label}: unknown rule \"${key}\" (allowed: ${Object.keys(RULE_KEYS).join(\", \")})`)\n if (AUTH_ONLY_RULE_KEYS.has(key) && type !== \"auth\") problems.push(`${label}: rule \"${key}\" only applies to auth collections`)\n const value = collection.rules[key]\n if (value !== null && typeof value !== \"string\") problems.push(`${label}: rule \"${key}\" must be a string or null`)\n }\n if (type === \"view\" && collection.rules) {\n for (const key of [\"create\", \"update\", \"delete\"]) {\n if (key in collection.rules) problems.push(`${label}: view collections are read-only; remove the \"${key}\" rule`)\n }\n }\n for (const field of collection.fields ?? []) {\n if (!field.name) problems.push(`${label}: a field has no name`)\n if (!FIELD_TYPES.has(field.type)) problems.push(`${label}.${field.name}: unknown field type \"${field.type}\"`)\n if (field.type === \"relation\" && !field.collection) problems.push(`${label}.${field.name}: relation fields need \"collection\" (the target collection name)`)\n if (field.type === \"select\" && !(Array.isArray(field.values) && field.values.length)) problems.push(`${label}.${field.name}: select fields need a \"values\" array`)\n }\n if (type === \"view\" && collection.fields?.length) problems.push(`${label}: view collections take their fields from viewQuery; remove \"fields\"`)\n if (collection.seed !== undefined && !Array.isArray(collection.seed)) problems.push(`${label}: \"seed\" must be an array of records`)\n }\n if (schema.rateLimits !== undefined && !Array.isArray(schema.rateLimits)) problems.push('\"rateLimits\" must be an array')\n for (const rule of Array.isArray(schema.rateLimits) ? schema.rateLimits : []) {\n if (!rule?.label || !(rule.maxRequests > 0) || !(rule.duration > 0)) {\n problems.push(`each rateLimits entry needs \"label\", \"maxRequests\" and \"duration\" (seconds): ${JSON.stringify(rule)}`)\n }\n }\n if (problems.length) fail(`schema.json has ${problems.length} problem(s):\\n - ${problems.join(\"\\n - \")}`)\n}\n\nfunction toApiField(field) {\n const { collection, ...rest } = field\n if (field.type !== \"relation\") return rest\n const collectionId = collections.get(collection)?.id\n if (!collectionId) fail(`Relation target \"${collection}\" does not exist. Add it to schema.json or fix the name.`)\n return { maxSelect: 1, cascadeDelete: false, ...rest, collectionId }\n}\n\nfunction mergeFields(existing, desired) {\n const byName = new Map((existing?.fields ?? []).map((field) => [field.name, field]))\n const merged = desired.map((field) => {\n const current = byName.get(field.name)\n if (current && current.type !== field.type) {\n fail(`Field \"${field.name}\" exists with type ${current.type}; changing it to ${field.type} would drop data. Use a new field name instead.`)\n }\n return current ? { ...current, ...field, id: current.id } : field\n })\n const desiredNames = new Set(desired.map((field) => field.name))\n const kept = (existing?.fields ?? []).filter((field) => !desiredNames.has(field.name))\n return [...kept.filter((field) => field.system), ...merged, ...kept.filter((field) => !field.system)]\n}\n\nfunction indexName(sql) {\n return INDEX_NAME.exec(sql)?.[1]\n}\n\nfunction indexDefinition(sql) {\n return sql.replace(INDEX_NAME, \"INDEX\").replace(/[`\"]/g, \"\").replace(/\\s+/g, \" \").trim().toLowerCase()\n}\n\nfunction mergeIndexes(existing, desired) {\n if (!desired) return existing ?? []\n const names = new Set(desired.map(indexName))\n const definitions = new Set(desired.map(indexDefinition))\n const kept = (existing ?? []).filter((sql) => !names.has(indexName(sql)) && !definitions.has(indexDefinition(sql)))\n return [...kept, ...desired]\n}\n\nfunction withTimestamps(collection, fields, existingFields = []) {\n if (collection.timestamps === false) return fields\n const present = (name) => fields.some((field) => field.name === name) || existingFields.some((field) => field.name === name)\n return [...fields, ...TIMESTAMPS.filter((timestamp) => !present(timestamp.name))]\n}\n\nasync function createMissingCollections(group) {\n for (const collection of group) {\n if (collections.has(collection.name)) continue\n const type = collection.type ?? \"base\"\n const body = { name: collection.name, type }\n if (type === \"view\") {\n body.viewQuery = collection.viewQuery\n } else {\n const plainFields = (collection.fields ?? []).filter((field) => field.type !== \"relation\")\n body.fields = withTimestamps(collection, plainFields)\n }\n const res = await request(base, \"/api/collections\", { method: \"POST\", token, body })\n if (res.status !== 200) fail(`Cannot create ${collection.name}: ${describeError(res)}`)\n console.log(`NEW ${collection.name}`)\n }\n}\n\nasync function updateFieldsAndIndexes(group) {\n for (const collection of group) {\n const existing = collections.get(collection.name)\n const body = {}\n if (existing.type === \"view\") {\n if (collection.viewQuery && collection.viewQuery !== existing.viewQuery) body.viewQuery = collection.viewQuery\n } else {\n const desired = withTimestamps(collection, (collection.fields ?? []).map(toApiField), existing.fields)\n body.fields = mergeFields(existing, desired)\n body.indexes = mergeIndexes(existing.indexes, collection.indexes)\n }\n if (collection.authOptions) Object.assign(body, collection.authOptions)\n if (!Object.keys(body).length) continue\n const res = await request(base, `/api/collections/${existing.id}`, { method: \"PATCH\", token, body })\n if (res.status !== 200) fail(`Cannot update ${collection.name}: ${describeError(res)}`)\n console.log(`SYNC ${collection.name} (${res.data.fields.length} fields, ${res.data.indexes.length} indexes)`)\n }\n}\n\nasync function applyRules() {\n for (const collection of wanted) {\n if (!collection.rules) continue\n const body = {}\n for (const [key, apiKey] of Object.entries(RULE_KEYS)) {\n if (key in collection.rules) body[apiKey] = collection.rules[key]\n }\n const res = await request(base, `/api/collections/${collections.get(collection.name).id}`, { method: \"PATCH\", token, body })\n if (res.status !== 200) fail(`Cannot set rules on ${collection.name}: ${describeError(res)}`)\n console.log(`RULES ${collection.name}`)\n }\n}\n\nasync function applyRateLimits() {\n if (!schema.rateLimits?.length) return\n const settings = await request(base, \"/api/settings\", { token })\n if (settings.status !== 200) fail(`Cannot read settings: ${describeError(settings)}`)\n const current = settings.data.rateLimits ?? { enabled: true, rules: [] }\n const rules = mergeRateLimitRules(current.rules ?? [], schema.rateLimits)\n const res = await request(base, \"/api/settings\", { method: \"PATCH\", token, body: { rateLimits: { ...current, enabled: true, rules } } })\n if (res.status !== 200) fail(`Cannot set rate limits: ${describeError(res)}`)\n console.log(`LIMIT ${schema.rateLimits.map((rule) => rule.label).join(\", \")}`)\n}\n\nasync function seedEmptyCollections() {\n for (const collection of wanted) {\n if (!collection.seed?.length) continue\n const recordsPath = `/api/collections/${collection.name}/records`\n const count = await request(base, `${recordsPath}?perPage=1&skipTotal=0`, { token })\n if (count.status !== 200) fail(`Cannot read ${collection.name}: ${describeError(count)}`)\n if (count.data.totalItems > 0) {\n console.log(`SEED ${collection.name} skipped (already has ${count.data.totalItems} records)`)\n continue\n }\n const inserted = []\n for (const record of collection.seed) {\n const res = await request(base, recordsPath, { method: \"POST\", token, body: record })\n if (res.status === 200) {\n inserted.push(res.data.id)\n continue\n }\n await removeRecords(recordsPath, inserted)\n const after = await request(base, `${recordsPath}?perPage=1&skipTotal=0`, { token })\n const left = after.status === 200 ? after.data.totalItems : null\n const cleanup = left === 0\n ? \"\"\n : ` ${left ?? \"Some\"} record(s) are still in ${collection.name} (a request that failed may still have been saved); delete them in the dashboard, or the next run skips this collection's seed.`\n fail(`Cannot seed ${collection.name} with ${JSON.stringify(record)}: ${describeError(res)}.${cleanup}`)\n }\n console.log(`SEED ${collection.name} (${collection.seed.length} records)`)\n }\n}\n\nasync function removeRecords(recordsPath, ids) {\n for (const id of ids) await request(base, `${recordsPath}/${id}`, { method: \"DELETE\", token })\n}\n"
|
|
294
|
+
"text": "import {\n baseUrlFrom,\n describeError,\n fail,\n listCollections,\n mergeRateLimitRules,\n readCredentials,\n readJson,\n request,\n superuserToken,\n wakeUp,\n} from \"./pb-lib.mjs\"\n\nconst args = process.argv.slice(2)\nconst checkOnly = args.includes(\"--check\")\nconst [schemaPath, credsPath] = args.filter((arg) => arg !== \"--check\")\nif (!schemaPath || (!credsPath && !checkOnly)) {\n fail(\"Usage: node pb-apply-schema.mjs <schema.json> <credentials.json> or node pb-apply-schema.mjs --check <schema.json>\")\n}\n\nconst RULE_KEYS = {\n list: \"listRule\",\n view: \"viewRule\",\n create: \"createRule\",\n update: \"updateRule\",\n delete: \"deleteRule\",\n auth: \"authRule\",\n manage: \"manageRule\",\n}\nconst AUTH_ONLY_RULE_KEYS = new Set([\"auth\", \"manage\"])\nconst COLLECTION_KEYS = new Set([\"name\", \"type\", \"rules\", \"fields\", \"indexes\", \"authOptions\", \"timestamps\", \"viewQuery\", \"seed\"])\nconst COLLECTION_TYPES = new Set([\"base\", \"auth\", \"view\"])\nconst FIELD_TYPES = new Set([\"text\", \"editor\", \"number\", \"bool\", \"email\", \"url\", \"date\", \"autodate\", \"select\", \"file\", \"relation\", \"json\", \"geoPoint\"])\nconst INDEX_NAME = /INDEX\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?[`\"]?(\\w+)[`\"]?/i\nconst TIMESTAMPS = [\n { name: \"created\", type: \"autodate\", onCreate: true, onUpdate: false },\n { name: \"updated\", type: \"autodate\", onCreate: true, onUpdate: true },\n]\n\nconst schema = readJson(schemaPath)\nconst wanted = Array.isArray(schema.collections) ? schema.collections : fail('schema.json needs a top-level \"collections\" array')\nvalidateSchema()\nif (checkOnly) {\n console.log(`OK ${schemaPath} is valid (${wanted.length} collections). Relation targets outside the file are checked when applied.`)\n process.exit(0)\n}\n\nconst creds = readCredentials(credsPath)\nconst base = baseUrlFrom(creds)\nawait wakeUp(base)\nconst token = await superuserToken(base, creds)\n\nconst isView = (collection) => (collection.type ?? \"base\") === \"view\"\nlet collections = await listCollections(base, token)\nawait createMissingCollections(wanted.filter((collection) => !isView(collection)))\ncollections = await listCollections(base, token)\nawait updateFieldsAndIndexes(wanted.filter((collection) => !isView(collection)))\nawait createMissingCollections(wanted.filter(isView))\ncollections = await listCollections(base, token)\nawait updateFieldsAndIndexes(wanted.filter(isView))\nawait applyRules()\nawait applyRateLimits()\nawait seedEmptyCollections()\nconsole.log(`DONE schema applied to ${base}`)\n\nfunction validateSchema() {\n const problems = []\n const names = new Set()\n for (const collection of wanted) {\n const label = collection.name ?? \"(unnamed)\"\n if (!collection.name || !/^[a-z_][a-z0-9_]*$/i.test(collection.name)) problems.push(`invalid collection name \"${collection.name}\"`)\n if (names.has(collection.name)) problems.push(`${label}: listed twice`)\n names.add(collection.name)\n for (const key of Object.keys(collection)) {\n if (!COLLECTION_KEYS.has(key)) problems.push(`${label}: unknown key \"${key}\" (allowed: ${[...COLLECTION_KEYS].join(\", \")})`)\n }\n const type = collection.type ?? \"base\"\n if (!COLLECTION_TYPES.has(type)) problems.push(`${label}: type must be base, auth or view`)\n if (type === \"view\" && !collection.viewQuery) problems.push(`${label}: view collections need \"viewQuery\"`)\n if (type !== \"view\" && collection.viewQuery) problems.push(`${label}: \"viewQuery\" only applies to type \"view\"`)\n for (const key of Object.keys(collection.rules ?? {})) {\n if (!(key in RULE_KEYS)) problems.push(`${label}: unknown rule \"${key}\" (allowed: ${Object.keys(RULE_KEYS).join(\", \")})`)\n if (AUTH_ONLY_RULE_KEYS.has(key) && type !== \"auth\") problems.push(`${label}: rule \"${key}\" only applies to auth collections`)\n const value = collection.rules[key]\n if (value !== null && typeof value !== \"string\") problems.push(`${label}: rule \"${key}\" must be a string or null`)\n }\n if (type === \"view\" && collection.rules) {\n for (const key of [\"create\", \"update\", \"delete\"]) {\n if (key in collection.rules) problems.push(`${label}: view collections are read-only; remove the \"${key}\" rule`)\n }\n }\n for (const field of collection.fields ?? []) {\n if (!field.name) problems.push(`${label}: a field has no name`)\n if (!FIELD_TYPES.has(field.type)) problems.push(`${label}.${field.name}: unknown field type \"${field.type}\"`)\n if (field.type === \"relation\" && !field.collection) problems.push(`${label}.${field.name}: relation fields need \"collection\" (the target collection name)`)\n if (field.type === \"select\" && !(Array.isArray(field.values) && field.values.length)) problems.push(`${label}.${field.name}: select fields need a \"values\" array`)\n }\n if (type === \"view\" && collection.fields?.length) problems.push(`${label}: view collections take their fields from viewQuery; remove \"fields\"`)\n if (collection.seed !== undefined && !Array.isArray(collection.seed)) problems.push(`${label}: \"seed\" must be an array of records`)\n }\n if (schema.rateLimits !== undefined && !Array.isArray(schema.rateLimits)) problems.push('\"rateLimits\" must be an array')\n for (const rule of Array.isArray(schema.rateLimits) ? schema.rateLimits : []) {\n if (!rule?.label || !(rule.maxRequests > 0) || !(rule.duration > 0)) {\n problems.push(`each rateLimits entry needs \"label\", \"maxRequests\" and \"duration\" (seconds): ${JSON.stringify(rule)}`)\n }\n }\n if (problems.length) fail(`schema.json has ${problems.length} problem(s):\\n - ${problems.join(\"\\n - \")}`)\n}\n\nfunction toApiField(field) {\n const { collection, ...rest } = field\n if (field.type !== \"relation\") return rest\n const collectionId = collections.get(collection)?.id\n if (!collectionId) fail(`Relation target \"${collection}\" does not exist. Add it to schema.json or fix the name.`)\n return { maxSelect: 1, cascadeDelete: false, ...rest, collectionId }\n}\n\nfunction mergeFields(existing, desired) {\n const byName = new Map((existing?.fields ?? []).map((field) => [field.name, field]))\n const merged = desired.map((field) => {\n const current = byName.get(field.name)\n if (current && current.type !== field.type) {\n fail(`Field \"${field.name}\" exists with type ${current.type}; changing it to ${field.type} would drop data. Use a new field name instead.`)\n }\n return current ? { ...current, ...field, id: current.id } : field\n })\n const desiredNames = new Set(desired.map((field) => field.name))\n const kept = (existing?.fields ?? []).filter((field) => !desiredNames.has(field.name))\n return [...kept.filter((field) => field.system), ...merged, ...kept.filter((field) => !field.system)]\n}\n\nfunction indexName(sql) {\n return INDEX_NAME.exec(sql)?.[1]\n}\n\nfunction indexDefinition(sql) {\n return sql.replace(INDEX_NAME, \"INDEX\").replace(/[`\"]/g, \"\").replace(/\\s+/g, \" \").trim().toLowerCase()\n}\n\nfunction mergeIndexes(existing, desired) {\n if (!desired) return existing ?? []\n const names = new Set(desired.map(indexName))\n const definitions = new Set(desired.map(indexDefinition))\n const kept = (existing ?? []).filter((sql) => !names.has(indexName(sql)) && !definitions.has(indexDefinition(sql)))\n return [...kept, ...desired]\n}\n\nfunction withTimestamps(collection, fields, existingFields = []) {\n if (collection.timestamps === false) return fields\n const present = (name) => fields.some((field) => field.name === name) || existingFields.some((field) => field.name === name)\n return [...fields, ...TIMESTAMPS.filter((timestamp) => !present(timestamp.name))]\n}\n\nasync function createMissingCollections(group) {\n for (const collection of group) {\n if (collections.has(collection.name)) continue\n const type = collection.type ?? \"base\"\n const body = { name: collection.name, type }\n if (type === \"view\") {\n body.viewQuery = collection.viewQuery\n } else {\n const plainFields = (collection.fields ?? []).filter((field) => field.type !== \"relation\")\n body.fields = withTimestamps(collection, plainFields)\n }\n const res = await request(base, \"/api/collections\", { method: \"POST\", token, body })\n if (res.status !== 200) fail(`Cannot create ${collection.name}: ${describeError(res)}`)\n console.log(`NEW ${collection.name}`)\n }\n}\n\nasync function updateFieldsAndIndexes(group) {\n for (const collection of group) {\n const existing = collections.get(collection.name)\n const body = {}\n if (existing.type === \"view\") {\n if (collection.viewQuery && collection.viewQuery !== existing.viewQuery) body.viewQuery = collection.viewQuery\n } else {\n const desired = withTimestamps(collection, (collection.fields ?? []).map(toApiField), existing.fields)\n body.fields = mergeFields(existing, desired)\n body.indexes = mergeIndexes(existing.indexes, collection.indexes)\n // A new field is writable under the old rules until applyRules() runs (it goes last because rules\n // may name fields of collections synced later), so lock the writes it will replace meanwhile. An\n // aborted run then leaves them superuser-only, not open.\n if (desired.some((field) => !existing.fields.some((f) => f.name === field.name))) {\n for (const key of [\"create\", \"update\"]) {\n if (key in (collection.rules ?? {})) body[RULE_KEYS[key]] = null\n }\n }\n }\n if (collection.authOptions) Object.assign(body, collection.authOptions)\n if (!Object.keys(body).length) continue\n const res = await request(base, `/api/collections/${existing.id}`, { method: \"PATCH\", token, body })\n if (res.status !== 200) fail(`Cannot update ${collection.name}: ${describeError(res)}`)\n console.log(`SYNC ${collection.name} (${res.data.fields.length} fields, ${res.data.indexes.length} indexes)`)\n }\n}\n\nasync function applyRules() {\n for (const collection of wanted) {\n if (!collection.rules) continue\n const body = {}\n for (const [key, apiKey] of Object.entries(RULE_KEYS)) {\n if (key in collection.rules) body[apiKey] = collection.rules[key]\n }\n const res = await request(base, `/api/collections/${collections.get(collection.name).id}`, { method: \"PATCH\", token, body })\n if (res.status !== 200) fail(`Cannot set rules on ${collection.name}: ${describeError(res)}`)\n console.log(`RULES ${collection.name}`)\n }\n}\n\nasync function applyRateLimits() {\n if (!schema.rateLimits?.length) return\n const settings = await request(base, \"/api/settings\", { token })\n if (settings.status !== 200) fail(`Cannot read settings: ${describeError(settings)}`)\n const current = settings.data.rateLimits ?? { enabled: true, rules: [] }\n const rules = mergeRateLimitRules(current.rules ?? [], schema.rateLimits)\n const res = await request(base, \"/api/settings\", { method: \"PATCH\", token, body: { rateLimits: { ...current, enabled: true, rules } } })\n if (res.status !== 200) fail(`Cannot set rate limits: ${describeError(res)}`)\n console.log(`LIMIT ${schema.rateLimits.map((rule) => rule.label).join(\", \")}`)\n}\n\nasync function seedEmptyCollections() {\n for (const collection of wanted) {\n if (!collection.seed?.length) continue\n const recordsPath = `/api/collections/${collection.name}/records`\n const count = await request(base, `${recordsPath}?perPage=1&skipTotal=0`, { token })\n if (count.status !== 200) fail(`Cannot read ${collection.name}: ${describeError(count)}`)\n if (count.data.totalItems > 0) {\n console.log(`SEED ${collection.name} skipped (already has ${count.data.totalItems} records)`)\n continue\n }\n const inserted = []\n for (const record of collection.seed) {\n const res = await request(base, recordsPath, { method: \"POST\", token, body: record })\n if (res.status === 200) {\n inserted.push(res.data.id)\n continue\n }\n await removeRecords(recordsPath, inserted)\n const after = await request(base, `${recordsPath}?perPage=1&skipTotal=0`, { token })\n const left = after.status === 200 ? after.data.totalItems : null\n const cleanup = left === 0\n ? \"\"\n : ` ${left ?? \"Some\"} record(s) are still in ${collection.name} (a request that failed may still have been saved); delete them in the dashboard, or the next run skips this collection's seed.`\n fail(`Cannot seed ${collection.name} with ${JSON.stringify(record)}: ${describeError(res)}.${cleanup}`)\n }\n console.log(`SEED ${collection.name} (${collection.seed.length} records)`)\n }\n}\n\nasync function removeRecords(recordsPath, ids) {\n for (const id of ids) await request(base, `${recordsPath}/${id}`, { method: \"DELETE\", token })\n}\n"
|
|
295
295
|
},
|
|
296
296
|
{
|
|
297
297
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/scripts/pb-lib.mjs",
|
|
298
|
-
"digest": "sha256:
|
|
299
|
-
"size":
|
|
298
|
+
"digest": "sha256:f4c95240fb7203c9b7ef11c007961524f71524e4391cde0bca8e25cffaee50e6",
|
|
299
|
+
"size": 4703,
|
|
300
300
|
"mimeType": "text/plain",
|
|
301
|
-
"text": "import fs from \"node:fs\"\n\nconst REQUEST_TIMEOUT_MS = 20000\nconst WAKE_UP_RETRY_DELAY_MS = 3000\nconst RETRYABLE_STATUSES = new Set([502, 503, 504])\nconst RETRYABLE_STATUSES_FOR_WRITES = new Set([503])\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\"])\n\nexport function readJson(path) {\n try {\n return JSON.parse(fs.readFileSync(path, \"utf8\"))\n } catch (error) {\n fail(`Cannot read ${path}: ${error.message}`)\n }\n}\n\nexport function readCredentials(path) {\n const creds = readJson(path)\n const mode = fs.statSync(path).mode\n const readableByOthers = (mode & 0o077) !== 0\n if (readableByOthers && process.platform !== \"win32\") {\n console.warn(`WARN ${path} is readable by other users; run: chmod 600 ${path}`)\n }\n return creds\n}\n\nexport function fail(message) {\n console.error(`ERROR ${message}`)\n process.exit(1)\n}\n\nexport function baseUrlFrom(creds) {\n const raw = creds.api_url ?? (creds.domain ? `https://${creds.domain}` : null)\n if (!raw) fail(\"The credentials file has no domain or api_url. Save the full hosting_pocketbase_create-backend response.\")\n const withScheme = /^https?:\\/\\//i.test(raw) ? raw : `https://${raw}`\n return withScheme.replace(/\\/+$/, \"\").replace(/\\/api$/i, \"\")\n}\n\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n\nexport async function request(base, path, { method = \"GET\", token, body, retries = 2 } = {}) {\n const canRetryNetworkErrors = SAFE_METHODS.has(method)\n const retryableStatuses = SAFE_METHODS.has(method) ? RETRYABLE_STATUSES : RETRYABLE_STATUSES_FOR_WRITES\n let lastError\n for (let attempt = 0; attempt <= retries; attempt++) {\n const isLastAttempt = attempt === retries\n try {\n const response = await fetch(`${base}${path}`, {\n method,\n headers: {\n Accept: \"application/json\",\n ...(body ? { \"Content-Type\": \"application/json\" } : {}),\n ...(token ? { Authorization: token } : {}),\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n if (retryableStatuses.has(response.status) && !isLastAttempt) {\n await sleep(WAKE_UP_RETRY_DELAY_MS)\n continue\n }\n const text = await response.text()\n let data = null\n try {\n data = text ? JSON.parse(text) : null\n } catch {\n data = text\n }\n return { status: response.status, data }\n } catch (error) {\n lastError = error\n if (!canRetryNetworkErrors || isLastAttempt) break\n await sleep(WAKE_UP_RETRY_DELAY_MS)\n }\n }\n return { status: 0, data: { message: lastError?.message ?? \"request failed\" } }\n}\n\nexport async function wakeUp(base) {\n const health = await request(base, \"/api/health\", { retries: 5 })\n if (health.status !== 200) {\n fail(`${base}/api/health returned ${health.status} (${health.data?.message ?? \"no message\"}). Check the domain and that the backend exists (hosting_pocketbase_backend).`)\n }\n}\n\nexport async function superuserToken(base, creds) {\n const email = creds.superuser_email\n const password = creds.superuser_password\n if (!email || !password) fail(\"The credentials file has no superuser_email or superuser_password.\")\n const res = await request(base, \"/api/collections/_superusers/auth-with-password\", {\n method: \"POST\",\n body: { identity: email, password },\n retries: 4,\n })\n if (res.status !== 200) {\n fail(\n `Superuser sign-in failed (${res.status}: ${res.data?.message ?? \"no message\"}). ` +\n \"If the password was lost, rotate it with hosting_pocketbase_set-superuser and save the response.\",\n )\n }\n return res.data.token\n}\n\nexport async function listCollections(base, token) {\n const res = await request(base, \"/api/collections?perPage=1000\", { token })\n if (res.status !== 200) fail(`Cannot list collections: ${describeError(res)}`)\n return new Map(res.data.items.map((item) => [item.name, item]))\n}\n\nexport function describeError(res) {\n const details = res.data?.data && Object.keys(res.data.data).length ? JSON.stringify(res.data.data) : \"\"\n return `${res.status} ${res.data?.message ?? \"\"} ${details}`.trim()\n}\n\nexport function mergeRateLimitRules(current, desired) {\n const keyOf = (rule) => `${rule.label}|${rule.audience ?? \"\"}`\n const desiredKeys = new Set(desired.map(keyOf))\n const normalized = desired.map((rule) => ({ audience: \"\", ...rule }))\n return [...current.filter((rule) => !desiredKeys.has(keyOf(rule))), ...normalized]\n}\n"
|
|
301
|
+
"text": "import fs from \"node:fs\"\n\nconst REQUEST_TIMEOUT_MS = 20000\nconst WAKE_UP_RETRY_DELAY_MS = 3000\nconst RETRYABLE_STATUSES = new Set([502, 503, 504])\nconst RETRYABLE_STATUSES_FOR_WRITES = new Set([503])\nconst SAFE_METHODS = new Set([\"GET\", \"HEAD\"])\n\nexport function readJson(path) {\n try {\n return JSON.parse(fs.readFileSync(path, \"utf8\"))\n } catch (error) {\n fail(`Cannot read ${path}: ${error.message}`)\n }\n}\n\nexport function readCredentials(path) {\n const creds = readJson(path)\n const mode = fs.statSync(path).mode\n const readableByOthers = (mode & 0o077) !== 0\n if (readableByOthers && process.platform !== \"win32\") {\n try {\n fs.chmodSync(path, 0o600)\n console.warn(`WARN ${path} was readable by other users; it is now mode 600. If this computer is shared, rotate the password with hosting_pocketbase_set-superuser.`)\n } catch {\n console.warn(`WARN ${path} is readable by other users; run: chmod 600 ${path}`)\n }\n }\n return creds\n}\n\nexport function fail(message) {\n console.error(`ERROR ${message}`)\n process.exit(1)\n}\n\nexport function baseUrlFrom(creds) {\n const raw = creds.api_url ?? (creds.domain ? `https://${creds.domain}` : null)\n if (!raw) fail(\"The credentials file has no domain or api_url. Save the full hosting_pocketbase_create-backend response.\")\n const withScheme = /^https?:\\/\\//i.test(raw) ? raw : `https://${raw}`\n return withScheme.replace(/\\/+$/, \"\").replace(/\\/api$/i, \"\")\n}\n\nconst sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))\n\nexport async function request(base, path, { method = \"GET\", token, body, retries = 2 } = {}) {\n const canRetryNetworkErrors = SAFE_METHODS.has(method)\n const retryableStatuses = SAFE_METHODS.has(method) ? RETRYABLE_STATUSES : RETRYABLE_STATUSES_FOR_WRITES\n let lastError\n for (let attempt = 0; attempt <= retries; attempt++) {\n const isLastAttempt = attempt === retries\n try {\n const response = await fetch(`${base}${path}`, {\n method,\n headers: {\n Accept: \"application/json\",\n ...(body ? { \"Content-Type\": \"application/json\" } : {}),\n ...(token ? { Authorization: token } : {}),\n },\n body: body ? JSON.stringify(body) : undefined,\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n if (retryableStatuses.has(response.status) && !isLastAttempt) {\n await sleep(WAKE_UP_RETRY_DELAY_MS)\n continue\n }\n const text = await response.text()\n let data = null\n try {\n data = text ? JSON.parse(text) : null\n } catch {\n data = text\n }\n return { status: response.status, data }\n } catch (error) {\n lastError = error\n if (!canRetryNetworkErrors || isLastAttempt) break\n await sleep(WAKE_UP_RETRY_DELAY_MS)\n }\n }\n return { status: 0, data: { message: lastError?.message ?? \"request failed\" } }\n}\n\nexport async function wakeUp(base) {\n const health = await request(base, \"/api/health\", { retries: 5 })\n if (health.status !== 200) {\n fail(`${base}/api/health returned ${health.status} (${health.data?.message ?? \"no message\"}). Check the domain and that the backend exists (hosting_pocketbase_backend).`)\n }\n}\n\nexport async function superuserToken(base, creds) {\n const email = creds.superuser_email\n const password = creds.superuser_password\n if (!email || !password) fail(\"The credentials file has no superuser_email or superuser_password.\")\n const res = await request(base, \"/api/collections/_superusers/auth-with-password\", {\n method: \"POST\",\n body: { identity: email, password },\n retries: 4,\n })\n if (res.status !== 200) {\n fail(\n `Superuser sign-in failed (${res.status}: ${res.data?.message ?? \"no message\"}). ` +\n \"If the password was lost, rotate it with hosting_pocketbase_set-superuser and save the response.\",\n )\n }\n return res.data.token\n}\n\nexport async function listCollections(base, token) {\n const res = await request(base, \"/api/collections?perPage=1000\", { token })\n if (res.status !== 200) fail(`Cannot list collections: ${describeError(res)}`)\n return new Map(res.data.items.map((item) => [item.name, item]))\n}\n\nexport function describeError(res) {\n const details = res.data?.data && Object.keys(res.data.data).length ? JSON.stringify(res.data.data) : \"\"\n return `${res.status} ${res.data?.message ?? \"\"} ${details}`.trim()\n}\n\nexport function mergeRateLimitRules(current, desired) {\n const keyOf = (rule) => `${rule.label}|${rule.audience ?? \"\"}`\n const desiredKeys = new Set(desired.map(keyOf))\n const normalized = desired.map((rule) => ({ audience: \"\", ...rule }))\n return [...current.filter((rule) => !desiredKeys.has(keyOf(rule))), ...normalized]\n}\n"
|
|
302
302
|
},
|
|
303
303
|
{
|
|
304
304
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/scripts/pb-verify.mjs",
|
|
305
|
-
"digest": "sha256:
|
|
306
|
-
"size":
|
|
305
|
+
"digest": "sha256:9d884d1cdedce1b25776e42e81d9ef87c3b2e17690cb7619e12b8e50b24660e1",
|
|
306
|
+
"size": 6427,
|
|
307
307
|
"mimeType": "text/plain",
|
|
308
|
-
"text": "import { execFileSync } from \"node:child_process\"\nimport { baseUrlFrom, listCollections, readCredentials, readJson, request, superuserToken } from \"./pb-lib.mjs\"\n\nconst REALTIME_PROBE_SECONDS = \"8\"\nconst PAGE_TIMEOUT_MS = 15000\n\nconst [credsPath, schemaPath] = process.argv.slice(2)\nif (!credsPath) {\n console.error(\"Usage: node pb-verify.mjs <credentials.json> [schema.json]\")\n process.exit(1)\n}\n\nconst creds = readCredentials(credsPath)\nconst schema = schemaPath ? readJson(schemaPath) : { collections: [] }\nconst base = baseUrlFrom(creds)\nlet failures = 0\nlet warnings = 0\n\nconst pass = (message) => console.log(`PASS ${message}`)\nconst warn = (message) => {\n warnings++\n console.log(`WARN ${message}`)\n}\nconst bad = (message) => {\n failures++\n console.log(`FAIL ${message}`)\n}\n\nconst health = await request(base, \"/api/health\", { retries: 5 })\nif (health.status !== 200) {\n bad(`/api/health returned ${health.status}; the backend is missing or still waking up. Retry in 10 s, then check hosting_pocketbase_backend.`)\n finish()\n}\npass(\"API is healthy\")\n\nconst token = await superuserToken(base, creds)\npass(\"superuser sign-in works\")\n\nconst byName = await listCollections(base, token)\n\nfor (const collection of schema.collections ?? []) {\n const live = byName.get(collection.name)\n if (!live) {\n bad(`collection ${collection.name} is missing; run pb-apply-schema.mjs`)\n continue\n }\n const missing = (collection.fields ?? []).filter((field) => !live.fields.some((f) => f.name === field.name)).map((f) => f.name)\n if (missing.length) bad(`${collection.name} is missing fields: ${missing.join(\", \")}`)\n else if (live.type !== \"view\") pass(`${collection.name} has all ${collection.fields?.length ?? 0} declared fields`)\n\n const timestampsWanted = collection.timestamps !== false && live.type !== \"view\"\n if (timestampsWanted && !live.fields.some((field) => field.name === \"created\")) {\n warn(`${collection.name} has no \"created\" field, so sort: \"-created\" fails; re-run pb-apply-schema.mjs`)\n }\n\n const recordsPath = `/api/collections/${collection.name}/records`\n const anonList = await request(base, `${recordsPath}?perPage=1`)\n if (live.listRule === null) {\n anonList.status === 403\n ? pass(`${collection.name}: visitors cannot list (superusers only)`)\n : bad(`${collection.name}: listRule is null but an anonymous list returned ${anonList.status}`)\n } else if (anonList.status === 200) {\n const scope = live.listRule === \"\" ? \"everyone\" : `rule \"${live.listRule}\"`\n pass(`${collection.name}: listing works, filtered by ${scope}`)\n } else {\n bad(`${collection.name}: anonymous list returned ${anonList.status} ${anonList.data?.message ?? \"\"}`)\n }\n\n if (live.type !== \"view\" && live.createRule === null) {\n const anonCreate = await request(base, recordsPath, { method: \"POST\", body: {} })\n anonCreate.status === 403\n ? pass(`${collection.name}: visitors cannot create`)\n : bad(`${collection.name}: createRule is null but an anonymous create returned ${anonCreate.status}`)\n }\n if (live.createRule === \"\" && live.type === \"base\") warn(`${collection.name}: anyone can create records; fine for a public form, otherwise tighten it`)\n if (live.updateRule === \"\" || live.deleteRule === \"\") warn(`${collection.name}: anyone can update or delete any record; this is almost never intended`)\n}\n\nconst settings = await request(base, \"/api/settings\", { token })\nconst limits = settings.data?.rateLimits\nif (limits?.enabled) {\n const summary = (limits.rules ?? []).map((rule) => `${rule.label}${rule.audience ? ` ${rule.audience}` : \"\"} ${rule.maxRequests}/${rule.duration}s`).join(\", \")\n pass(`rate limits per IP: ${summary}`)\n}\nif (settings.data?.smtp && !settings.data.smtp.enabled) {\n console.log(\"INFO outgoing mail (SMTP) is off: verification and password-reset emails are not sent\")\n}\n\nfunction probeRealtime(protocol) {\n try {\n const out = execFileSync(\"curl\", [\"-sS\", \"-N\", protocol, \"--max-time\", REALTIME_PROBE_SECONDS, \"-H\", \"Accept: text/event-stream\", `${base}/api/realtime`], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n return out.includes(\"PB_CONNECT\") ? \"ok\" : \"no-event\"\n } catch (error) {\n if (error.code === \"ENOENT\") return \"no-curl\"\n return String(error.stdout ?? \"\").includes(\"PB_CONNECT\") ? \"ok\" : \"no-event\"\n }\n}\n\nconst http2 = probeRealtime(\"--http2\")\nif (http2 === \"no-curl\") {\n warn(\"curl is not installed, so realtime was not checked; open the site in two tabs and check a change appears in both\")\n} else {\n http2 === \"ok\" ? pass(\"realtime connects over HTTP/2 (browsers)\") : bad(\"realtime does not connect over HTTP/2; see troubleshooting.md\")\n probeRealtime(\"--http1.1\") === \"ok\"\n ? pass(\"realtime connects over HTTP/1.1 (Node.js clients, dev proxies)\")\n : warn(\"realtime does not connect over HTTP/1.1: browsers are fine, Node.js subscribers need the workaround in troubleshooting.md\")\n}\n\nconst dashboard = await fetch(`${base}/_/`, { signal: AbortSignal.timeout(PAGE_TIMEOUT_MS) }).catch(() => null)\ndashboard?.status === 200 ? pass(`dashboard is at ${base}/_/`) : bad(`dashboard returned ${dashboard?.status ?? \"no response\"}`)\n\nconst home = await fetch(`${base}/`, { signal: AbortSignal.timeout(PAGE_TIMEOUT_MS) }).catch(() => null)\nconst homeText = home ? await home.text() : \"\"\nif (!home || home.status >= 400) bad(`the website itself returned ${home?.status ?? \"no response\"}; deploy the frontend`)\nelse if (/<title>\\s*Coming soon\\s*<\\/title>/i.test(homeText)) {\n warn(\"the website still shows Hostinger's placeholder page; deploy the frontend\")\n} else pass(\"the website is serving the app\")\n\nfinish()\n\nfunction finish() {\n console.log(`\\n${failures ? \"NOT READY\" : \"READY\"}: ${failures} failed, ${warnings} warnings`)\n process.exit(failures ? 1 : 0)\n}\n"
|
|
308
|
+
"text": "import { execFileSync } from \"node:child_process\"\nimport { homedir } from \"node:os\"\nimport path from \"node:path\"\nimport { baseUrlFrom, listCollections, readCredentials, readJson, request, superuserToken } from \"./pb-lib.mjs\"\n\nconst REALTIME_PROBE_SECONDS = \"8\"\nconst PAGE_TIMEOUT_MS = 15000\n\nconst [credsPath, schemaPath] = process.argv.slice(2)\nif (!credsPath) {\n console.error(\"Usage: node pb-verify.mjs <credentials.json> [schema.json]\")\n process.exit(1)\n}\n\nconst creds = readCredentials(credsPath)\nconst schema = schemaPath ? readJson(schemaPath) : { collections: [] }\nconst base = baseUrlFrom(creds)\nlet failures = 0\nlet warnings = 0\n\nconst pass = (message) => console.log(`PASS ${message}`)\nconst warn = (message) => {\n warnings++\n console.log(`WARN ${message}`)\n}\nconst bad = (message) => {\n failures++\n console.log(`FAIL ${message}`)\n}\n\nconst health = await request(base, \"/api/health\", { retries: 5 })\nif (health.status !== 200) {\n bad(`/api/health returned ${health.status}; the backend is missing or still waking up. Retry in 10 s, then check hosting_pocketbase_backend.`)\n finish()\n}\npass(\"API is healthy\")\n\nconst token = await superuserToken(base, creds)\npass(\"superuser sign-in works\")\n\nconst byName = await listCollections(base, token)\n\nfor (const collection of schema.collections ?? []) {\n const live = byName.get(collection.name)\n if (!live) {\n bad(`collection ${collection.name} is missing; run pb-apply-schema.mjs`)\n continue\n }\n const missing = (collection.fields ?? []).filter((field) => !live.fields.some((f) => f.name === field.name)).map((f) => f.name)\n if (missing.length) bad(`${collection.name} is missing fields: ${missing.join(\", \")}`)\n else if (live.type !== \"view\") pass(`${collection.name} has all ${collection.fields?.length ?? 0} declared fields`)\n\n const timestampsWanted = collection.timestamps !== false && live.type !== \"view\"\n if (timestampsWanted && !live.fields.some((field) => field.name === \"created\")) {\n warn(`${collection.name} has no \"created\" field, so sort: \"-created\" fails; re-run pb-apply-schema.mjs`)\n }\n\n const recordsPath = `/api/collections/${collection.name}/records`\n const anonList = await request(base, `${recordsPath}?perPage=1`)\n if (live.listRule === null) {\n anonList.status === 403\n ? pass(`${collection.name}: visitors cannot list (superusers only)`)\n : bad(`${collection.name}: listRule is null but an anonymous list returned ${anonList.status}`)\n } else if (anonList.status === 200) {\n const scope = live.listRule === \"\" ? \"everyone\" : `rule \"${live.listRule}\"`\n pass(`${collection.name}: listing works, filtered by ${scope}`)\n } else {\n bad(`${collection.name}: anonymous list returned ${anonList.status} ${anonList.data?.message ?? \"\"}`)\n }\n\n if (live.type !== \"view\" && live.createRule === null) {\n const anonCreate = await request(base, recordsPath, { method: \"POST\", body: {} })\n anonCreate.status === 403\n ? pass(`${collection.name}: visitors cannot create`)\n : bad(`${collection.name}: createRule is null but an anonymous create returned ${anonCreate.status}`)\n }\n if (live.createRule === \"\" && live.type === \"base\") warn(`${collection.name}: anyone can create records; fine for a public form, otherwise tighten it`)\n if (live.updateRule === \"\" || live.deleteRule === \"\") warn(`${collection.name}: anyone can update or delete any record; this is almost never intended`)\n}\n\nconst settings = await request(base, \"/api/settings\", { token })\nconst limits = settings.data?.rateLimits\nif (limits?.enabled) {\n const summary = (limits.rules ?? []).map((rule) => `${rule.label}${rule.audience ? ` ${rule.audience}` : \"\"} ${rule.maxRequests}/${rule.duration}s`).join(\", \")\n pass(`rate limits per IP: ${summary}`)\n}\nif (settings.data?.smtp && !settings.data.smtp.enabled) {\n console.log(\"INFO outgoing mail (SMTP) is off: verification and password-reset emails are not sent\")\n}\n\n// curl is found by name, and Windows looks in the working directory (the user's project, maybe a\n// cloned repository) before PATH, as does a relative PATH entry elsewhere: run it from the home folder\n// with only absolute PATH entries, as connect/launch.mjs does for npx.\nconst curlEnv = { ...process.env }\nfor (const key of Object.keys(curlEnv).filter((k) => k.toUpperCase() === \"PATH\")) {\n curlEnv[key] = curlEnv[key].split(path.delimiter).filter((p) => path.isAbsolute(p)).join(path.delimiter)\n}\n\nfunction probeRealtime(protocol) {\n try {\n const out = execFileSync(\"curl\", [\"-sS\", \"-N\", protocol, \"--max-time\", REALTIME_PROBE_SECONDS, \"-H\", \"Accept: text/event-stream\", `${base}/api/realtime`], {\n cwd: homedir(),\n env: curlEnv,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n return out.includes(\"PB_CONNECT\") ? \"ok\" : \"no-event\"\n } catch (error) {\n if (error.code === \"ENOENT\") return \"no-curl\"\n return String(error.stdout ?? \"\").includes(\"PB_CONNECT\") ? \"ok\" : \"no-event\"\n }\n}\n\nconst http2 = probeRealtime(\"--http2\")\nif (http2 === \"no-curl\") {\n warn(\"curl is not installed, so realtime was not checked; open the site in two tabs and check a change appears in both\")\n} else {\n http2 === \"ok\" ? pass(\"realtime connects over HTTP/2 (browsers)\") : bad(\"realtime does not connect over HTTP/2; see troubleshooting.md\")\n probeRealtime(\"--http1.1\") === \"ok\"\n ? pass(\"realtime connects over HTTP/1.1 (Node.js clients, dev proxies)\")\n : warn(\"realtime does not connect over HTTP/1.1: browsers are fine, Node.js subscribers need the workaround in troubleshooting.md\")\n}\n\nconst dashboard = await fetch(`${base}/_/`, { signal: AbortSignal.timeout(PAGE_TIMEOUT_MS) }).catch(() => null)\ndashboard?.status === 200 ? pass(`dashboard is at ${base}/_/`) : bad(`dashboard returned ${dashboard?.status ?? \"no response\"}`)\n\nconst home = await fetch(`${base}/`, { signal: AbortSignal.timeout(PAGE_TIMEOUT_MS) }).catch(() => null)\nconst homeText = home ? await home.text() : \"\"\nif (!home || home.status >= 400) bad(`the website itself returned ${home?.status ?? \"no response\"}; deploy the frontend`)\nelse if (/<title>\\s*Coming soon\\s*<\\/title>/i.test(homeText)) {\n warn(\"the website still shows Hostinger's placeholder page; deploy the frontend\")\n} else pass(\"the website is serving the app\")\n\nfinish()\n\nfunction finish() {\n console.log(`\\n${failures ? \"NOT READY\" : \"READY\"}: ${failures} failed, ${warnings} warnings`)\n process.exit(failures ? 1 : 0)\n}\n"
|
|
309
309
|
},
|
|
310
310
|
{
|
|
311
311
|
"uri": "skill://hostinger-headless/steps/04-content-model/pocketbase/troubleshooting.md",
|
|
@@ -372,10 +372,10 @@ const skills: Skill[] = [
|
|
|
372
372
|
},
|
|
373
373
|
{
|
|
374
374
|
"uri": "skill://hostinger-headless/steps/06-frontend/SKILL.md",
|
|
375
|
-
"digest": "sha256:
|
|
376
|
-
"size":
|
|
375
|
+
"digest": "sha256:310321cd6787ac255d41f662ffed5d5aee9a4b520654893efb0e22b2f9396010",
|
|
376
|
+
"size": 12069,
|
|
377
377
|
"mimeType": "text/markdown",
|
|
378
|
-
"text": "---\nname: headless-step-frontend\ndescription: \"Step 6 (frontend) of the Hostinger Headless flow. Builds the website that renders the backend's content. Figures out (or confirms) the framework — defaulting to Next.js SSR — implements the look already chosen in design.md (the design step's contract), and builds the source into src/. Only ask for the clarifications you actually need.\"\n---\n\n# headless-step-frontend\n\nBuild the site's frontend against the backend from `site.json`, implementing the look the design step\nalready chose and wrote to **`design.md`** (plus the logo in `brand/`). The design is decided; this step\nis where it becomes real code. There's no per-framework recipe — use good judgement, follow `design.md`\nas the contract, and ask only for the clarifications you genuinely need. **Out:** source in the site\nworkspace `~/.hostinger/<domain>/src/`.\n\n> **Build mode \"Bring your own frontend\"? Read this first (any backend).** Read `brief.md` → **Build mode**.\n> When it is **Bring your own frontend**, follow [`bring-your-own-frontend.md`](bring-your-own-frontend.md): wire the user's own project to the\n> backend instead of scaffolding one. When it is **Agent designs and builds**, proceed normally.\n\n> **PocketBase backend?** A `pocketbase` brief has **no CMS/store**: the app's data lives in the\n> PocketBase backend recorded in `site.json → pocketbase`, its collections in `pocketbase/schema.json`\n> (and the `## Data` section of `content-model.md`), and its fixed copy in `content-model.md`. A new\n> app is scaffolded from `brief.md` and `design.md` and binds its forms and views to the collections\n> in `pocketbase/schema.json`; an existing app under **Agent designs and builds** starts from its\n> source, keeps its screens and features, wires its data to the backend and rebuilds its UI to\n> `design.md`. In Step 3 follow the PocketBase bullet.\n\n## Step 1 — Pick the framework (guess → default → confirm)\n\n**The rendering is already decided in `brief.md` → Rendering** (SSR or SSG, set during refine). Honour\nit, and the backend constraint:\n\n- **Ecommerce → SSR required** (carts/search need per-request rendering). Any SSR framework works —\n Next.js is the default, not a requirement (Express, Nuxt, SvelteKit, etc. are all fine).\n- **WordPress + WooCommerce → SSR required** (same reason — cart/checkout need per-request rendering).\n- **WordPress → SSG (Astro)** when the brief says SSG, otherwise **SSR (Next.js default)**.\n- **PocketBase → the app's own stack.** An **existing app** keeps its current framework (don't impose one), including\n one rebuilt under **Agent designs and builds**; a\n **new app** uses whatever fits the brief (SSR or SPA). Either way it deploys as a Node.js app (Step 8) —\n an SSR app runs a server, a SPA builds to static output. The app must not serve anything under\n `/api` or `/_`: PocketBase owns those paths on this domain, so server routes go under another prefix\n (`/server`): Next.js `app/server/…` never `app/api/…`, and likewise no Nuxt `server/api/`, SvelteKit\n `src/routes/api/` or Astro `src/pages/api/`.\n- Map rendering → framework: **`ssr` → Next.js**, **`ssg` → Astro** — unless the brief/prompt explicitly\n names another supported framework, in which case use that.\n\nSupported frameworks are the ones in deploy's *Build configurations* table (`../08-deploy/SKILL.md`).\n\nConfirm the framework with the user in one line only if the brief left it open. Record the choice in\n`state.json`:\n\n```json\n{ \"frontend\": { \"framework\": \"nextjs\", \"rendering\": \"ssr\" } }\n```\n\nIf the brief is silent, default to **Next.js SSR**.\n\n## Step 2 — Implement `design.md` (don't re-design)\n\nThe look was already chosen and written by the design step. **Read `~/.hostinger/<domain>/design.md` and\nimplement it faithfully** — tokens (colour, type, spacing), components, per-page composition, imagery and\naccessibility — plus the logo files in `brand/`. Don't re-run design questions or invent a new direction here.\n\n- Treat `design.md` as the contract: the built pages should match its tokens, type scale, components and\n per-page composition, and the 8-point grid / WCAG 2.2 AA rules it carries.\n- Build the **logo** and favicon exactly as `design.md` → **Logo** → *Use* says; never recolour or redraw\n what is in `brand/`.\n- If `design.md` is **missing** (e.g. a resumed older build), fall back to `brief.md → Design direction`\n (reference site, colours, brand, adjectives) and a tasteful, accessible default — but prefer `design.md`\n whenever it exists.\n- **Don't gate on approval here** — the result is shown at **validate** (Step 7).\n\n**Only ask about the code, and only if it matters** (design decisions belong in the design step):\n- Where the **source should live** — default `~/.hostinger/<domain>/src/`; ask only if they want a\n specific folder or an existing repo.\n- **Git** — initialise / connect / push (default: a local project, no remote).\n- A specific **component library** or technical must-have, if they implied one.\n\n## Step 3 — Build against the backend\n\nTwo phases around the instance barrier (see the top-level `SKILL.md`): scaffold + build the shell while\nprovision settles, then wire live data once `provision.status == \"completed\"`.\n\nRead the backend from `site.json`:\n\n- **WordPress** → `urls.rest_api` (`wp/v2`), public read. Content is in the posts/pages/categories/media\n the content-model push created; nav/plan come from `content-model.md`. Map each item's **SEO** from its\n `yoast_head_json` into the page `<head>` (title, description, Open Graph, JSON-LD schema) — Yoast is\n installed by default at provision (`site.json → seo.enabled: true`). If `seo.enabled` is `false`\n (Yoast absent), fall back to generating per-page title/description/OG tags from each item's content.\n - **Decode WordPress text.** WordPress returns titles and names HTML-encoded (`Tea & Cake`,\n `don’t`). Add the `entities` package and, in the one data module, run every title, name\n and SEO field you render as plain text (posts, pages, terms, Yoast, Store API products and\n categories) through `decodeHTML` once; strip an excerpt's tags first if you show it as text.\n Leave HTML fields (`content.rendered`, an excerpt shown as HTML) as they are, and never inject a\n decoded field as raw HTML.\n - **Contact form** (`site.json → contact_form.enabled: true`, any WordPress backend) → render the\n contact page's form and submit it **client-side** to `contact_form.feedback_url` exactly as\n [`../04-content-model/wordpress/contact-form.md`](../04-content-model/wordpress/contact-form.md) §3\n says. When `contact_form.enabled` is `false` or absent, render the contact page with plain contact\n details and **no form** — graceful, like disabled checkout; never half-build.\n- **WordPress + WooCommerce** (`site.json → woocommerce.enabled: true`) → the WordPress bullet above **plus**\n the store, read over the **public WooCommerce Store API** (`site.json → urls.store_api`): follow\n [`../04-content-model/wordpress/woocommerce.md`](../04-content-model/wordpress/woocommerce.md) §2 for\n the calls, headers and minor-unit prices, and §4 for `site.json → woocommerce.payment_enabled` (while\n `false`, a graceful disabled-checkout state, no `/checkout` call, not a build error). **Never embed a\n consumer key client-side.**\n- **Ecommerce** → the public Hostinger Storefront Core V2 API: follow [`ecommerce.md`](ecommerce.md).\n- **PocketBase** → the `pocketbase` SDK against the backend on the same domain, following\n [`../04-content-model/pocketbase/frontend.md`](../04-content-model/pocketbase/frontend.md) (skip its\n static `.htaccess` section: a headless site deploys as Node.js and keeps no `.htaccess`). In the one\n data module: `new PocketBase(<origin>)` where the origin is `window.location.origin` in the browser\n and `site.json → urls.site` in local dev and on the server, then `pb.autoCancellation(false)` once.\n Build filters with `pb.filter()`, load a list then subscribe to it for live views, and unsubscribe on\n unmount. Build each form and view against the fields in `pocketbase/schema.json`, and show a rule\n rejection (a 400 with no field errors, a 404 on update) as a normal \"not allowed\" state. Add the\n sign-in form only when the schema has an auth collection visitors use\n ([`../04-content-model/pocketbase/auth.md`](../04-content-model/pocketbase/auth.md)). A public form\n includes its recipe's honeypot field, empty and hidden. **The superuser password never reaches the\n frontend**; server-side superuser work reads `PB_URL`, `PB_SUPERUSER_EMAIL` and\n `PB_SUPERUSER_PASSWORD` from the app's environment variables (`frontend.md`, Node.js apps). For an\n existing app, keep its screens and swap its data calls to the backend.\n\nGuidelines (framework-agnostic):\n\n- **One data module** is the single place that talks to the backend (e.g. `src/lib/data.ts`) — one file\n to inspect, one base URL to switch. Keep it swappable so the shell can build against stubs first.\n- **Fetch at request time for SSR** (fresh content, no rebuild); a static build fetches at build time.\n- **A failed or incomplete fetch is an error, not a silent empty/placeholder.** Planned content missing\n from the API is a build error too — a site that builds with holes ships with holes. *(On PocketBase\n the planned content is the fixed pages plus the seed records.)*\n- **`content-model.md` is the source for what should exist** (pages, nav, collections mapping) — on\n every backend; on PocketBase it also carries the `## Data` section.\n- **No `.htaccess`** in the project (deploy would overwrite the live one); don't commit `node_modules`\n or build output.\n- Set `engines.node` to `22` (the deploy builds on Node 22).\n- **Next.js 16+ only:** set the `build` script to `next build --webpack`, not plain `next build`. Next.js\n 16 defaults `next build` to **Turbopack**, whose native compiler needs a newer glibc than the Hostinger\n build server has, so a Turbopack build fails on deploy and won't fall back to webpack. Webpack builds\n clean there. The `--webpack` flag exists only on Next.js 16+; on **Next.js 15.x** leave the build script\n as plain `next build` (it already defaults to webpack). (Alternative: pin Next.js to `15.x`, keeping\n plain `next build`.)\n\n## Step 4 — Hand off\n\nConfirm the project builds clean locally against the live backend, looks right at desktop and phone\nwidth (below), no placeholder/fixture content remains, and `state.json → frontend` matches what you\nbuilt. Update `state.json` (`stage: \"validate\"`).\nValidate (Step 7) owns the clean rebuild + user preview; deploy (Step 8) ships it with the `app_type`\nand output directory that match the chosen framework + rendering.\n\n**Visual check.** With the site running locally against the live backend, look at the home page and one\npage of each template (e.g. a post, a product, the contact page) at desktop and phone width. Take all the\nscreenshots first, then open them all in one turn where your tool can open several images at once, since\neach separate look costs a model turn. Don't tile several pages onto one image or take one tall\nfull-page shot: the viewer shrinks big images, and a shrunk page hides small bugs like a wrapped line.\nAfter a fix, re-shoot only what changed. Phone width is where most layout bugs show. Headless Chrome\nwon't size a window below ~500 px, so a phone-width window comes back cropped: set a 390 px viewport\n(e.g. Playwright), or put one route in 1280 px and 390 px iframes side by side on a local page to get\nboth widths in one image. The live site runs this same build, so it needs no screenshots; deploy checks\nthat it serves.\n\n> **PocketBase:** the app reaches the live backend from local dev (`frontend.md`, Local development),\n> so check one list and one create against it here, then delete the test records before handing over.\n"
|
|
378
|
+
"text": "---\nname: headless-step-frontend\ndescription: \"Step 6 (frontend) of the Hostinger Headless flow. Builds the website that renders the backend's content. Figures out (or confirms) the framework — defaulting to Next.js SSR — implements the look already chosen in design.md (the design step's contract), and builds the source into src/. Only ask for the clarifications you actually need.\"\n---\n\n# headless-step-frontend\n\nBuild the site's frontend against the backend from `site.json`, implementing the look the design step\nalready chose and wrote to **`design.md`** (plus the logo in `brand/`). The design is decided; this step\nis where it becomes real code. There's no per-framework recipe — use good judgement, follow `design.md`\nas the contract, and ask only for the clarifications you genuinely need. **Out:** source in the site\nworkspace `~/.hostinger/<domain>/src/`.\n\n> **Build mode \"Bring your own frontend\"? Read this first (any backend).** Read `brief.md` → **Build mode**.\n> When it is **Bring your own frontend**, follow [`bring-your-own-frontend.md`](bring-your-own-frontend.md): wire the user's own project to the\n> backend instead of scaffolding one. When it is **Agent designs and builds**, proceed normally.\n\n> **PocketBase backend?** A `pocketbase` brief has **no CMS/store**: the app's data lives in the\n> PocketBase backend recorded in `site.json → pocketbase`, its collections in `pocketbase/schema.json`\n> (and the `## Data` section of `content-model.md`), and its fixed copy in `content-model.md`. A new\n> app is scaffolded from `brief.md` and `design.md` and binds its forms and views to the collections\n> in `pocketbase/schema.json`; an existing app under **Agent designs and builds** starts from its\n> source, keeps its screens and features, wires its data to the backend and rebuilds its UI to\n> `design.md`. In Step 3 follow the PocketBase bullet.\n\n## Step 1 — Pick the framework (guess → default → confirm)\n\n**The rendering is already decided in `brief.md` → Rendering** (SSR or SSG, set during refine). Honour\nit, and the backend constraint:\n\n- **Ecommerce → SSR required** (carts/search need per-request rendering). Any SSR framework works —\n Next.js is the default, not a requirement (Express, Nuxt, SvelteKit, etc. are all fine).\n- **WordPress + WooCommerce → SSR required** (same reason — cart/checkout need per-request rendering).\n- **WordPress → SSG (Astro)** when the brief says SSG, otherwise **SSR (Next.js default)**.\n- **PocketBase → the app's own stack.** An **existing app** keeps its current framework (don't impose one), including\n one rebuilt under **Agent designs and builds**; a\n **new app** uses whatever fits the brief (SSR or SPA). Either way it deploys as a Node.js app (Step 8) —\n an SSR app runs a server, a SPA builds to static output. The app must not serve anything under\n `/api` or `/_`: PocketBase owns those paths on this domain, so server routes go under another prefix\n (`/server`): Next.js `app/server/…` never `app/api/…`, and likewise no Nuxt `server/api/`, SvelteKit\n `src/routes/api/` or Astro `src/pages/api/`.\n- Map rendering → framework: **`ssr` → Next.js**, **`ssg` → Astro** — unless the brief/prompt explicitly\n names another supported framework, in which case use that.\n\nSupported frameworks are the ones in deploy's *Build configurations* table (`../08-deploy/SKILL.md`).\n\nConfirm the framework with the user in one line only if the brief left it open. Record the choice in\n`state.json`:\n\n```json\n{ \"frontend\": { \"framework\": \"nextjs\", \"rendering\": \"ssr\" } }\n```\n\nIf the brief is silent, default to **Next.js SSR**.\n\n## Step 2 — Implement `design.md` (don't re-design)\n\nThe look was already chosen and written by the design step. **Read `~/.hostinger/<domain>/design.md` and\nimplement it faithfully** — tokens (colour, type, spacing), components, per-page composition, imagery and\naccessibility — plus the logo files in `brand/`. Don't re-run design questions or invent a new direction here.\n\n- Treat `design.md` as the contract: the built pages should match its tokens, type scale, components and\n per-page composition, and the 8-point grid / WCAG 2.2 AA rules it carries.\n- Build the **logo** and favicon exactly as `design.md` → **Logo** → *Use* says; never recolour or redraw\n what is in `brand/`.\n- If `design.md` is **missing** (e.g. a resumed older build), fall back to `brief.md → Design direction`\n (reference site, colours, brand, adjectives) and a tasteful, accessible default — but prefer `design.md`\n whenever it exists.\n- **Don't gate on approval here** — the result is shown at **validate** (Step 7).\n\n**Only ask about the code, and only if it matters** (design decisions belong in the design step):\n- Where the **source should live** — default `~/.hostinger/<domain>/src/`; ask only if they want a\n specific folder or an existing repo.\n- **Git** — initialise / connect / push (default: a local project, no remote).\n- A specific **component library** or technical must-have, if they implied one.\n\n## Step 3 — Build against the backend\n\nTwo phases around the instance barrier (see the top-level `SKILL.md`): scaffold + build the shell while\nprovision settles, then wire live data once `provision.status == \"completed\"`.\n\nRead the backend from `site.json`:\n\n- **WordPress** → `urls.rest_api` (`wp/v2`), public read. Content is in the posts/pages/categories/media\n the content-model push created; nav/plan come from `content-model.md`. Map each item's **SEO** from its\n `yoast_head_json` into the page `<head>` (title, description, Open Graph, JSON-LD schema) — Yoast is\n installed by default at provision (`site.json → seo.enabled: true`). If `seo.enabled` is `false`\n (Yoast absent), fall back to generating per-page title/description/OG tags from each item's content.\n - **Decode WordPress text.** WordPress returns titles and names HTML-encoded (`Tea & Cake`,\n `don’t`). Add the `entities` package and, in the one data module, run every title, name\n and SEO field you render as plain text (posts, pages, terms, Yoast, Store API products and\n categories) through `decodeHTML` once; strip an excerpt's tags first if you show it as text.\n Leave HTML fields (`content.rendered`, an excerpt shown as HTML) as they are, and never inject a\n decoded field as raw HTML.\n - **Contact form** (`site.json → contact_form.enabled: true`, any WordPress backend) → render the\n contact page's form and submit it **client-side** to `contact_form.feedback_url` exactly as\n [`../04-content-model/wordpress/contact-form.md`](../04-content-model/wordpress/contact-form.md) §3\n says. When `contact_form.enabled` is `false` or absent, render the contact page with plain contact\n details and **no form** — graceful, like disabled checkout; never half-build.\n- **WordPress + WooCommerce** (`site.json → woocommerce.enabled: true`) → the WordPress bullet above **plus**\n the store, read over the **public WooCommerce Store API** (`site.json → urls.store_api`): follow\n [`../04-content-model/wordpress/woocommerce.md`](../04-content-model/wordpress/woocommerce.md) §2 for\n the calls, headers and minor-unit prices, and §4 for `site.json → woocommerce.payment_enabled` (while\n `false`, a graceful disabled-checkout state, no `/checkout` call, not a build error). **Never embed a\n consumer key client-side.**\n- **Ecommerce** → the public Hostinger Storefront Core V2 API: follow [`ecommerce.md`](ecommerce.md).\n- **PocketBase** → the `pocketbase` SDK against the backend on the same domain, following\n [`../04-content-model/pocketbase/frontend.md`](../04-content-model/pocketbase/frontend.md) (skip its\n static `.htaccess` section: a headless site deploys as Node.js and keeps no `.htaccess`). In the one\n data module: `new PocketBase(<origin>)` where the origin is `window.location.origin` in the browser\n and `site.json → urls.site` in local dev and on the server, then `pb.autoCancellation(false)` once.\n Build filters with `pb.filter()`, load a list then subscribe to it for live views, and unsubscribe on\n unmount. Build each form and view against the fields in `pocketbase/schema.json`, and show a rule\n rejection (a 400 with no field errors, a 404 on update) as a normal \"not allowed\" state. Add the\n sign-in form only when the schema has an auth collection visitors use\n ([`../04-content-model/pocketbase/auth.md`](../04-content-model/pocketbase/auth.md)). A public form\n includes its recipe's honeypot field, empty and hidden. **The superuser password never reaches the\n frontend**; server-side superuser work reads `PB_URL`, `PB_SUPERUSER_EMAIL` and\n `PB_SUPERUSER_PASSWORD` from the app's environment variables and signs in **its own** server-only\n client, never the shared `pb` that renders pages for visitors (`frontend.md`, Node.js apps). For an\n existing app, keep its screens and swap its data calls to the backend.\n\nGuidelines (framework-agnostic):\n\n- **One data module** is the single place that talks to the backend (e.g. `src/lib/data.ts`) — one file\n to inspect, one base URL to switch. Keep it swappable so the shell can build against stubs first.\n- **Fetch at request time for SSR** (fresh content, no rebuild); a static build fetches at build time.\n- **A failed or incomplete fetch is an error, not a silent empty/placeholder.** Planned content missing\n from the API is a build error too — a site that builds with holes ships with holes. *(On PocketBase\n the planned content is the fixed pages plus the seed records.)*\n- **`content-model.md` is the source for what should exist** (pages, nav, collections mapping) — on\n every backend; on PocketBase it also carries the `## Data` section.\n- **No `.htaccess`** in the project (deploy would overwrite the live one); don't commit `node_modules`\n or build output.\n- Set `engines.node` to `22` (the deploy builds on Node 22).\n- **Next.js 16+ only:** set the `build` script to `next build --webpack`, not plain `next build`. Next.js\n 16 defaults `next build` to **Turbopack**, whose native compiler needs a newer glibc than the Hostinger\n build server has, so a Turbopack build fails on deploy and won't fall back to webpack. Webpack builds\n clean there. The `--webpack` flag exists only on Next.js 16+; on **Next.js 15.x** leave the build script\n as plain `next build` (it already defaults to webpack). (Alternative: pin Next.js to `15.x`, keeping\n plain `next build`.)\n\n## Step 4 — Hand off\n\nConfirm the project builds clean locally against the live backend, looks right at desktop and phone\nwidth (below), no placeholder/fixture content remains, and `state.json → frontend` matches what you\nbuilt. Update `state.json` (`stage: \"validate\"`).\nValidate (Step 7) owns the clean rebuild + user preview; deploy (Step 8) ships it with the `app_type`\nand output directory that match the chosen framework + rendering.\n\n**Visual check.** With the site running locally against the live backend, look at the home page and one\npage of each template (e.g. a post, a product, the contact page) at desktop and phone width. Take all the\nscreenshots first, then open them all in one turn where your tool can open several images at once, since\neach separate look costs a model turn. Don't tile several pages onto one image or take one tall\nfull-page shot: the viewer shrinks big images, and a shrunk page hides small bugs like a wrapped line.\nAfter a fix, re-shoot only what changed. Phone width is where most layout bugs show. Headless Chrome\nwon't size a window below ~500 px, so a phone-width window comes back cropped: set a 390 px viewport\n(e.g. Playwright), or put one route in 1280 px and 390 px iframes side by side on a local page to get\nboth widths in one image. The live site runs this same build, so it needs no screenshots; deploy checks\nthat it serves.\n\n> **PocketBase:** the app reaches the live backend from local dev (`frontend.md`, Local development),\n> so check one list and one create against it here, then delete the test records before handing over.\n"
|
|
379
379
|
},
|
|
380
380
|
{
|
|
381
381
|
"uri": "skill://hostinger-headless/steps/06-frontend/bring-your-own-frontend.md",
|
|
@@ -4,4 +4,4 @@ import { startServer } from '../core/runtime.js';
|
|
|
4
4
|
import tools from '../core/tools/agency-hosting.js';
|
|
5
5
|
import instructions from '../core/instructions.agency-hosting.js';
|
|
6
6
|
|
|
7
|
-
startServer({ name: 'hostinger-agency-hosting-mcp', version: '4.5.
|
|
7
|
+
startServer({ name: 'hostinger-agency-hosting-mcp', version: '4.5.2', tools, instructions });
|
|
@@ -4,4 +4,4 @@ import { startServer } from '../core/runtime.js';
|
|
|
4
4
|
import tools from '../core/tools/agency-hosting.js';
|
|
5
5
|
import instructions from '../core/instructions.agency-hosting.js';
|
|
6
6
|
|
|
7
|
-
startServer({ name: 'hostinger-agency-hosting-mcp', version: '4.5.
|
|
7
|
+
startServer({ name: 'hostinger-agency-hosting-mcp', version: '4.5.2', tools, instructions });
|
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
import { startServer } from '../core/runtime.js';
|
|
4
4
|
import tools from '../core/tools/agent-readiness.js';
|
|
5
5
|
|
|
6
|
-
startServer({ name: 'hostinger-agent-readiness-mcp', version: '4.5.
|
|
6
|
+
startServer({ name: 'hostinger-agent-readiness-mcp', version: '4.5.2', tools });
|
|
@@ -3,4 +3,4 @@
|
|
|
3
3
|
import { startServer } from '../core/runtime.js';
|
|
4
4
|
import tools from '../core/tools/agent-readiness.js';
|
|
5
5
|
|
|
6
|
-
startServer({ name: 'hostinger-agent-readiness-mcp', version: '4.5.
|
|
6
|
+
startServer({ name: 'hostinger-agent-readiness-mcp', version: '4.5.2', tools });
|
package/src/servers/all.js
CHANGED
|
@@ -5,4 +5,4 @@ import tools from '../core/tools/all.js';
|
|
|
5
5
|
import instructions from '../core/instructions.js';
|
|
6
6
|
import skills from '../core/skills.js';
|
|
7
7
|
|
|
8
|
-
startServer({ name: 'hostinger-api-mcp', version: '4.5.
|
|
8
|
+
startServer({ name: 'hostinger-api-mcp', version: '4.5.2', tools, instructions, skills });
|
package/src/servers/all.ts
CHANGED
|
@@ -5,4 +5,4 @@ import tools from '../core/tools/all.js';
|
|
|
5
5
|
import instructions from '../core/instructions.js';
|
|
6
6
|
import skills from '../core/skills.js';
|
|
7
7
|
|
|
8
|
-
startServer({ name: 'hostinger-api-mcp', version: '4.5.
|
|
8
|
+
startServer({ name: 'hostinger-api-mcp', version: '4.5.2', tools, instructions, skills });
|
package/src/servers/billing.js
CHANGED
package/src/servers/billing.ts
CHANGED
package/src/servers/dns.js
CHANGED
package/src/servers/dns.ts
CHANGED
package/src/servers/domains.js
CHANGED
package/src/servers/domains.ts
CHANGED
package/src/servers/ecommerce.js
CHANGED
package/src/servers/ecommerce.ts
CHANGED
package/src/servers/gpu.js
CHANGED
package/src/servers/gpu.ts
CHANGED
package/src/servers/horizons.js
CHANGED
package/src/servers/horizons.ts
CHANGED
package/src/servers/hosting.js
CHANGED
|
@@ -4,4 +4,4 @@ import { startServer } from '../core/runtime.js';
|
|
|
4
4
|
import tools from '../core/tools/hosting.js';
|
|
5
5
|
import instructions from '../core/instructions.js';
|
|
6
6
|
|
|
7
|
-
startServer({ name: 'hostinger-hosting-mcp', version: '4.5.
|
|
7
|
+
startServer({ name: 'hostinger-hosting-mcp', version: '4.5.2', tools, instructions });
|
package/src/servers/hosting.ts
CHANGED
|
@@ -4,4 +4,4 @@ import { startServer } from '../core/runtime.js';
|
|
|
4
4
|
import tools from '../core/tools/hosting.js';
|
|
5
5
|
import instructions from '../core/instructions.js';
|
|
6
6
|
|
|
7
|
-
startServer({ name: 'hostinger-hosting-mcp', version: '4.5.
|
|
7
|
+
startServer({ name: 'hostinger-hosting-mcp', version: '4.5.2', tools, instructions });
|
package/src/servers/mail.js
CHANGED
package/src/servers/mail.ts
CHANGED
package/src/servers/reach.js
CHANGED
package/src/servers/reach.ts
CHANGED
package/src/servers/vps.js
CHANGED
package/src/servers/vps.ts
CHANGED
package/src/servers/wordpress.js
CHANGED
package/src/servers/wordpress.ts
CHANGED