create-ilorb 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE-API.md ADDED
@@ -0,0 +1,108 @@
1
+ # LICENSE-API — license server contract (v1)
2
+
3
+ What `create-overture` expects from the store's license API (operasourcecode.com). **The store does not exist yet**: this
4
+ contract is implemented by the FAKE server `tools/fake-license-server.mjs` (tests, end-to-end and demo) and is what the
5
+ real Worker must fulfil. House standard: Worker + D1 on the CONNECTING account, errors in the Core format
6
+ (`{ "error": { "code": "snake_case", "message": "…" } }`).
7
+
8
+ Base: `https://api.operasourcecode.com` (in the CLI: `--license-server` / `OVERTURE_LICENSE_SERVER`).
9
+
10
+ ## Keys (Ed25519)
11
+
12
+ - The store has one Ed25519 pair per period (`kid`, e.g. `osc-2026-11`). The **private** key lives only in the Worker (secret).
13
+ The **public** key (32 bytes, base64) is embedded in the CLI at `src/license/keys.ts` → `LICENSE_KEYS`.
14
+ - Rotating keys: ship a CLI with the new public key **before** issuing with it; the old ones stay in the list
15
+ as long as there are valid licenses signed with them.
16
+ - Today only the **test** key `test-2026-10` exists (private key in `test/fixtures/license-test-key.pem`, on purpose):
17
+ the CLI only accepts a license signed by it when the license server is `localhost`. It unlocks nothing real —
18
+ the server delivers the templates, and the real server does not accept the test `kid`.
19
+
20
+ ## License key (what the buyer receives by e-mail)
21
+
22
+ ```
23
+ osc1.<payload em base64url>.<assinatura Ed25519 em base64url>
24
+ assinatura = Ed25519(privada[kid], "osc1.<payload em base64url>")
25
+ ```
26
+ payload (JSON):
27
+ ```json
28
+ { "v": 1, "kid": "osc-2026-11", "lid": "lic_01J…", "products": ["chat"], "email": "comprador@empresa.com",
29
+ "type": "regular", "iat": 1792700000, "exp": null }
30
+ ```
31
+ | field | meaning |
32
+ |---|---|
33
+ | `lid` | license id in the store |
34
+ | `products` | ids of the unlocked products (`chat`, `consultas`…) or `["*"]` for a bundle |
35
+ | `type` | `regular` or `extended` (what each allows: the owner decides; the CLI only displays it) |
36
+ | `exp` | unix seconds or `null` (never expires). Support/updates have their own date at activation |
37
+
38
+ The CLI checks **offline** (signature, known `kid`, `exp`, product) before calling the API. An Envato purchase code
39
+ (`xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`) cannot be verified offline: only its format.
40
+
41
+ ## `POST /v1/licenses/activate`
42
+
43
+ Request:
44
+ ```json
45
+ {
46
+ "credential": { "type": "license", "key": "osc1.…" },
47
+ "product": "chat",
48
+ "installId": "0b9c…-uuid",
49
+ "machine": "sha256(hostname|usuário) truncado em 32 hex — sem dado pessoal",
50
+ "cliVersion": "0.1.0",
51
+ "target": "cloud"
52
+ }
53
+ ```
54
+ or, via Envato: `"credential": { "type": "envato", "purchaseCode": "a1b2c3d4-…" }`.
55
+
56
+ The server:
57
+ 1. **Own license:** checks the signature with the private key of the `kid`, `exp`, revocation and the product.
58
+ 2. **Envato:** calls `GET https://api.envato.com/v3/market/author/sale?code=<purchase code>` with the author's personal
59
+ token (Worker secret), checks the item (Envato item id ↔ product), refund and the buyer. Stores the
60
+ result (cache) so it does not hit Envato on every installation.
61
+ 3. **Idempotent activation:** the same (`license` or `purchase code`) + the same `installId` returns **the same activation**
62
+ (does not use another slot). A new installation counts as 1 up to the limit of the license type.
63
+ 4. Generates the templates link (signed, expires in minutes) and the signed **receipt**.
64
+
65
+ Response `200`:
66
+ ```json
67
+ {
68
+ "activation": {
69
+ "id": "act_…", "licenseId": "lic_…", "product": "chat", "type": "regular", "source": "opera",
70
+ "buyerEmail": "comprador@empresa.com", "supportUntil": "2027-10-23T00:00:00.000Z",
71
+ "activationsUsed": 1, "activationsLimit": 3, "activatedAt": "2026-10-23T12:00:00.000Z"
72
+ },
73
+ "receipt": "oscr1.<payload>.<assinatura>",
74
+ "templates": { "version": "0.1.0", "url": "https://…/v1/templates/chat-0.1.0.tgz?…", "sha256": "<64 hex>", "size": 739790 }
75
+ }
76
+ ```
77
+ Receipt (`oscr1`, same Ed25519 key): `{ "v": 1, "kid", "aid": "<activation.id>", "lid", "product", "installId", "iat" }`.
78
+ The CLI rejects it (`license_receipt_invalid`) if the signature does not match or if `aid`/`installId`/`product` do not
79
+ match the request — an arbitrary server cannot "activate" in place of the store, and a receipt cannot be used for another installation.
80
+
81
+ Errors (the CLI translates each code to pt/es/en with what to do):
82
+
83
+ | status | `error.code` | when |
84
+ |---|---|---|
85
+ | 400 | `invalid_request` | missing field |
86
+ | 400 | `license_malformed` / `purchase_code_malformed` | format |
87
+ | 401 | `license_bad_signature` | signature does not match |
88
+ | 403 | `license_revoked` | canceled (refund, abuse) |
89
+ | 403 / 404 | `license_wrong_product` | license for another product / nonexistent product |
90
+ | 409 | `license_activation_limit` | installation limit |
91
+ | 410 | `license_expired` | expired |
92
+ | 404 | `purchase_code_invalid` | Envato does not know it |
93
+ | 422 | `purchase_code_wrong_item` | belongs to another item |
94
+ | 403 | `purchase_code_refunded` | purchase refunded |
95
+ | 503 | `envato_unavailable` | Envato did not respond |
96
+ | 429 | `rate_limited` (+ `retryAfter` in seconds) | too many attempts |
97
+ | 5xx | anything else | the CLI shows `license_server_error` |
98
+
99
+ ## `GET /v1/templates/<product>-<version>.tgz?…`
100
+
101
+ The link that came with the activation (signed, short-lived). Returns the `.tar.gz` with the product folders **in the same
102
+ structure as the repository** (`overture-core/…`, `overture-chat/…`, `vendor/opera-signal-<commit>/…`) — without `node_modules`, `dist`,
103
+ `.wrangler`, `.dev.vars`, screenshots, and **without `vendor/…/apps/chat/wrangler.jsonc`** (Opera's production config). The CLI
104
+ checks the `sha256` before opening it and deletes the file after copying.
105
+
106
+ ## Not yet used by the CLI (suggestion for v2)
107
+ - `POST /v1/licenses/deactivate { activationId, receipt }` — frees the slot (the store panel should also have the button).
108
+ - `GET /v1/products/<id>/latest` — newest version of the templates, for a future `create-overture update`.
package/README.md CHANGED
@@ -1,3 +1,286 @@
1
- # Temporary Holding Version
1
+ # create-overture — installation in 1 command
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ```sh
4
+ npm create overture@latest chat # Overture Chat (messaging app: iOS, Android and web)
5
+ npm create overture@latest widgets # Overture Widgets (free: Opera chat and calls on any site)
6
+ npm create overture@latest consultas # Overture Consultas (scheduling + payment through the Core + video at a set time)
7
+ npm create overture@latest status # Overture Status (public status page + uptime monitor; no Opera)
8
+ npm create overture@latest agenda # Overture Agenda (in-person booking + payment through the Core; public booking page + widget; no Opera)
9
+ npm create overture@latest sites # Overture Sites (block-based site published to R2 from the panel; no Opera)
10
+ npm create overture@latest starter # Overture Starter (SaaS base: organizations, plans and billing through the Core; web app on Pages)
11
+ npm create overture@latest link # Overture Link (shortener, QR, bio, plans; click queue only on the paid plan)
12
+ npm create overture@latest imoveis # Overture Imóveis (real-estate portal: SEO site + advertiser app + panel)
13
+ npm create overture@latest quiz # Overture Quiz (quiz game; optional sample questions)
14
+ npm create overture@latest helpcenter # Overture Help Center (help center + widget + requests by e-mail)
15
+ npm create overture@latest classificados # Overture Classificados (classifieds site with SEO + app + moderation)
16
+ # same thing: npx create-overture chat · with options: npm create overture@latest widgets -- --target local
17
+ ```
18
+
19
+ It asks for the license, asks a few questions, generates the buyer's project (Core + the product) already with the name, ids and theme,
20
+ creates everything in the **buyer's Cloudflare account** (D1, R2, Workers, Pages), applies the migrations, publishes, configures
21
+ login through `/v1/admin/*` and prints the URLs and next steps. Running it again is safe: it continues where it stopped and does not
22
+ duplicate anything. With `--target local` it brings up Core, Chat API, panel and app **on the computer**; the chat itself is Opera's
23
+ in the cloud, with an **Opera TEST app** owned by the buyer (the Opera chat server is not in the package).
24
+
25
+ > ⚠️ **npm name:** package `create-overture` (unscoped; free on npm on 2026-10-23) → `npm create overture`. The internal
26
+ > packages use the scope `@operasourcecode/overture-*` (the `@overture` scope belongs to another organization). Nothing has been published.
27
+
28
+ Node 20+ (tested on 22), pnpm (`npm i -g pnpm` or `corepack enable`). No runtime dependencies: just Node.
29
+
30
+ ## Products (one `ProductSpec` per product in `src/products.ts`)
31
+ Everything that differs from one product to another lives in a single registry — the steps (`src/steps.ts`), generation (`src/generate.ts`),
32
+ `scripts/dev-local.mjs` and the fake license server only read the spec. New product = one new record + the templates.
33
+
34
+ | | `chat` | `widgets` | `consultas` |
35
+ |---|---|---|---|
36
+ | Product Worker / D1 | `<app>-chat` / `<app>-chat` (`overture-chat/api/workers`) | `<app>-widgets` / `<app>-widgets` (`overture-widgets/api/workers`) | `<app>-consultas` / `<app>-consultas` (`overture-consultas/api/workers`) |
37
+ | Generated secrets (`.overture/secrets.env`) | `CHAT_SECRETS_KEY` | `WIDGETS_VISITOR_KEY`, `WIDGETS_SECRETS_KEY` | `PAYMENTS_TOKEN`, `PAYMENTS_CALLBACK_SECRET` — **the Core Worker also receives both** (same value: product → Core and the signed callback Core → product) |
38
+ | Product Worker secrets | `CORE_SERVICE_TOKEN`, `SECRETS_KEY` (+ `OPERA_APP_SECRET`, `OPERA_CALLBACK_SECRET` if provided) | `CORE_SERVICE_TOKEN`, `VISITOR_KEY`, `SECRETS_KEY` (+ the Opera ones and `RESEND_API_KEY`, if provided) | `CORE_SERVICE_TOKEN`, `PAYMENTS_TOKEN`, `PAYMENTS_CALLBACK_SECRET` (+ the Opera ones and `RESEND_API_KEY`, if provided) |
39
+ | Worker vars | `CORE_URL`, `PRODUCT`, `OPERA_APP_ID`, `OPERA_CHAT_URL`, `OPERA_ROOMS_URL`, `CALL_MEDIA`, `APNS_BUNDLE_ID` | `CORE_URL`, `PUBLIC_URL` (the snippet), `OPERA_APP_ID`, `OPERA_CHAT_URL`, `OPERA_ROOMS_URL`, `CALL_MEDIA`, `CORS_ORIGINS` (= the panel), `EMAIL_FROM` | `CORE_URL`, `PRODUCT`, `PUBLIC_URL`, `APP_URL` (local), `OPERA_*`, `CALL_MEDIA`, `NOTIFY_MODE` (cloud `live`, local `log`), `CORS_ORIGINS` (panel + local web app), `EMAIL_FROM` · **cron `* * * * *`** (24 h/15 min reminders, expired locks; local: `dev-local` calls `/__scheduled` every minute on the Core and on Consultas) |
40
+ | R2 | `<app>-media` | — (messages and media stay in Opera) | — |
41
+ | App | Expo (`overture-chat/app/react-native`): bundle id, `app.json`, `eas.json`, `expo export` in local | — (no mobile app: no bundle id, no EAS) | Expo (`overture-consultas/app/react-native`, `EXPO_PUBLIC_CONSULTAS_API_URL`) |
42
+ | Build before deploy | — | `node build.mjs` in `overture-widgets/web/js` → `api/workers/src/generated/assets.ts` (the widget goes INSIDE the Worker; widget changed → build + deploy only the Widgets Worker) | — |
43
+ | Core `settings.products` | `{id:"chat", name:<app name>, platforms:[ios,android,web], apiUrl}` | `{id:"widgets", name:"Overture Widgets", platforms:[web], apiUrl}` | `{id:"consultas", name:<app name>, platforms:[ios,android,web], apiUrl}` (`apiUrl` is where the payment callbacks go) |
44
+ | Copied folders | the whole Core + `overture-chat/{api/workers,app/react-native,web/react}` + `vendor/…/packages` | Core (Worker, panel, `app/react-native/packages` + `tsconfig.base.json`) + `overture-widgets/{api/workers,web/js,web/react,shared}` + `vendor/…/packages` — **without** `overture-chat/`, the Core demo app and `overture-widgets/e2e` | Core (Worker with payments + `PAYMENTS-API.md`, panel, `app/react-native/packages`) + `overture-consultas/{api/workers,app/react-native,web/react}` + `vendor/opera-signal-475ec74/packages` |
45
+ | Local (ports starting at 8871) | auth, api, panel, app | auth, api, panel and the **test page** with the snippet (`http://localhost:<site>/?w=<widget id>`) | auth, api, panel, app; payments SIMULATED by the Core |
46
+
47
+ ### Status, Agenda and Sites (no Opera: no Opera keys, no TEST app in local)
48
+
49
+ | | `status` | `agenda` | `sites` |
50
+ |---|---|---|---|
51
+ | Worker / D1 | `<app>-status` / `<app>-status` (`overture-status/api/workers`; Durable Object `Probe` only with `REGIONS`) | `<app>-agenda` / `<app>-agenda` (`overture-agenda/api/workers`) | `<app>-sites` / `<app>-sites` (`overture-sites/api/workers`; Workers Assets `./public`, `run_worker_first`) |
52
+ | Product R2 | — | — | `<app>-sites-files` (binding `FILES`: published versions and media) |
53
+ | Generated secrets | `STATUS_SECRETS_KEY` (32 bytes → the Worker's `SECRETS_KEY`: encrypts Telegram/webhooks, signs "sign out") | `PAYMENTS_TOKEN`, `PAYMENTS_CALLBACK_SECRET` — **the Core receives both** (same value) | — |
54
+ | Worker secrets | `SECRETS_KEY` (+ `RESEND_API_KEY`, if provided) — **no** `CORE_SERVICE_TOKEN` | `CORE_SERVICE_TOKEN`, `PAYMENTS_TOKEN`, `PAYMENTS_CALLBACK_SECRET` (+ `RESEND_API_KEY`) | only the optional ones: `RESEND_API_KEY`, `TURNSTILE_SECRET` (env at installation, never a flag) |
55
+ | Vars | `CORE_URL`, `PRODUCT`, `PUBLIC_URL` (the custom domain, if `--status-domain`), `NOTIFY_MODE` (cloud `live`, local `log`), `ENVIRONMENT`, `CORS_ORIGINS` (= panel), `EMAIL_FROM` · **cron `* * * * *`** (checks) | `CORE_URL`, `PRODUCT`, `PUBLIC_URL`, `NOTIFY_MODE`, `ENVIRONMENT`, `CORS_ORIGINS`, `EMAIL_FROM` · **cron `* * * * *`** (reminders, locks) | `CORE_URL`, `PRODUCT`, `PUBLIC_URL` (= the site), `NOTIFY_MODE`, `ENVIRONMENT`, `CORS_ORIGINS`, `EMAIL_FROM` · no cron |
56
+ | `settings.products` | `{id:"status", name:"Overture Status", platforms:[web], apiUrl}` | `{id:"agenda", name:<app name>, platforms:[ios,android,web], apiUrl}` | `{id:"sites", name:<app name>, platforms:[web], apiUrl}` |
57
+ | Copied folders | Core (Worker, panel, `app/react-native/packages` — with the **OFL fonts** the Core serves at `/v1/fonts/` and the Status page uses —, `THEME-API.md`) + `overture-status/{api/workers,web/react,README.md}` | Core (with payments) + `overture-agenda/{api/workers,web/react,web/embed,app/react-native}` | Core (packages: the server imports the theme) + `overture-sites/{api/workers,web/react,README.md}` |
58
+ | Local (3 ports: auth, api, panel) | the page at `http://localhost:<api>/`; `dev-local` calls `/__scheduled` every minute | 5 ports (+ app and booking page); payments SIMULATED; cron every minute | publishing writes to local R2; the site at `http://localhost:<api>/` |
59
+ | Custom domain | `--status-domain status.empresa.com` → `routes: [{pattern, custom_domain:true}]` + `PUBLIC_URL` (zone in the same account; token with Zone · Workers Routes · Edit) | — | manual (Worker Custom Domain + `PUBLIC_URL`), in the next steps |
60
+
61
+ ### Starter and Link (no Opera; both bill through the Core: `PAYMENTS_TOKEN`/`PAYMENTS_CALLBACK_SECRET` identical on both Workers)
62
+
63
+ | | `starter` | `link` |
64
+ |---|---|---|
65
+ | Worker / D1 / R2 | `<app>-starter` / `<app>-starter` / — | `<app>-link` / `<app>-link` / `<app>-link-media` (binding `MEDIA`) |
66
+ | Pages | `<app>-admin` **and `<app>-app`** (the Expo web export; the URL becomes `urls.app` → `APP_URL`, `EXPO_PUBLIC_WEB_URL`, CORS of Starter and Core) | `<app>-admin` |
67
+ | Worker secrets | `PAYMENTS_TOKEN`, `PAYMENTS_CALLBACK_SECRET` (+ `RESEND_API_KEY`) — no `ADMIN_TOKEN`/`SERVICE_TOKEN`/`MASTER_KEY` | `PAYMENTS_*` + optional ones from the environment: `CF_API_TOKEN`, `CF_ZONE_ID`, `SAFE_BROWSING_KEY` |
68
+ | Vars | `CORE_URL`, `PRODUCT`, `APP_URL`, `NOTIFY_MODE`, `CORS_ORIGINS`, `ENVIRONMENT` (cloud only), `EMAIL_FROM` | `CORE_URL`, `PRODUCT`, `PUBLIC_URL` (the short domain, `--short-domain`), `SHORT_HOSTS` (from the template), `APP_URL`, `CORS_ORIGINS`, `ENVIRONMENT` |
69
+ | Cron | `0 * * * *` (local: `dev-local` calls it hourly) | `17 * * * *` |
70
+ | App | `EXPO_PUBLIC_STARTER_API_URL` + `EXPO_PUBLIC_WEB_URL` (`expo export --clear` local and in the cloud) | `EXPO_PUBLIC_LINK_API_URL` |
71
+ | Extra question | — | **"do you have the paid Workers plan?"** (`--workers-paid` / `--no-workers-paid`; `--yes` = no): yes → creates the `<app>-link-clicks` queue and enables `queues` (producer `CLICKS` + consumer) in `wrangler.jsonc`; no → clicks go straight to D1. Local: never a queue |
72
+ | Theme | — | the alias `overture-theme` → `./theme/entry.ts` → `../../../../overture-core/…` works the same in the buyer's project (the test checks that the files exist) |
73
+
74
+ ### Imóveis, Quiz, Help Center and Classificados (no Opera)
75
+
76
+ | | `imoveis` | `quiz` | `helpcenter` | `classificados` |
77
+ |---|---|---|---|---|
78
+ | Worker / D1 / R2 | `<app>-imoveis` / same / `<app>-imoveis-media` (`MEDIA`) | `<app>-quiz` / same / `<app>-quiz-media` (`MEDIA`) | `<app>-helpcenter` / same / `<app>-helpcenter-files` (`FILES`) | `<app>-classificados` / same (0001–0004) / `<app>-classificados-media` (`MEDIA`) |
79
+ | Pages | panel | panel + **`<app>-app`** (the web game) | panel | panel + **`<app>-app`** |
80
+ | Generated secrets → Worker | `PAYMENTS_*` (Core too) + `CORE_SERVICE_TOKEN` | `PAYMENTS_*` (Core too) — no ADMIN/SERVICE | `HELPCENTER_SIGNING_KEY` → `SIGNING_KEY` + `CORE_SERVICE_TOKEN` (+ `TURNSTILE_SECRET` from the environment) | `PAYMENTS_*` (Core too) + `CONTACT_KEY` + `CORE_SERVICE_TOKEN` |
81
+ | Cron | `17 * * * *` | `0 * * * *` | `* * * * *` | `*/5 * * * *` (`dev-local` calls it every 5 min) |
82
+ | App (`expo export --clear`) | `EXPO_PUBLIC_IMOVEIS_API_URL` | `EXPO_PUBLIC_QUIZ_API_URL` | — (the widget is compiled into the Worker: prebuild `web/js/build.mjs`) | `EXPO_PUBLIC_CLASSIFICADOS_API_URL` (`app.json` keeps the `expo-image-picker` plugin) |
83
+ | Fonts | Worker static assets (Core folder) | — | Worker static assets (Core folder) | `<CORE_URL>/v1/fonts/` |
84
+ | Extra | — | **sample questions** (`--sample-data`/`--no-sample-data`; question; default yes in local, no in the cloud): the CLI signs in as the owner through its OWN first-access link (`ADMIN_TOKEN` → `/v1/auth/bootstrap`) and does `POST /v1/admin/import/commit`; the owner's link comes later and overrides this one | **manual step** for Email Routing ("Send to a Worker" + Subaddressing) on the final screen and in the generated README | `--site-domain` (route + `PUBLIC_URL`); the 4 steps after installing; **checks** (`ProductSpec.smoke`: health, site, sitemap, panel 401, plans with a way to pay) — they warn, they do not abort |
85
+
86
+ **Core — `settings.accountUrl`:** the installation writes `<panel>/account` (the panel's Account screen, `routes.ts`) — the "Sair de
87
+ todos os aparelhos" button in the new-login e-mail; `settings.notifyNewLogin` stays at the Core default (on). Cloud and local.
88
+
89
+ **Agenda — public booking page (`overture-agenda/web/embed`, `ProductSpec.webBuild`):** `pnpm run build` with
90
+ `VITE_AGENDA_API_URL` = this installation's API (the CLI also writes the `<meta name="agenda-api">` of `index.html`, as its
91
+ README asks). In the cloud the `dist/` (page + `embed.js`) goes to the Pages project `<app>-agenda` (`pages` with key `site`, URL in
92
+ `urls.site` → the Worker's `APP_URL`, CORS of Agenda and Core); in local, the `site` port. The Expo app uses
93
+ `EXPO_PUBLIC_AGENDA_API_URL` (`expo export --clear`) and the panel pages are found by glob.
94
+
95
+ **Core — fonts (`/v1/fonts/*`):** the Core's `wrangler.jsonc` has `assets` (binding `FONTS`) at
96
+ `../../app/react-native/packages/theme/assets/fonts`; every product copies `packages/`, so the path holds in the copy (the
97
+ test checks it in every product), `wrangler deploy` uploads the assets and local `wrangler dev` serves them (the e2e tests request
98
+ `<core>/v1/fonts/fonts.css`: 200 with CORS `*`).
99
+
100
+ **Core R2 in every installation:** the Core's `wrangler.jsonc` has the `THEME_BUCKET` binding (appearance logo/favicon). In the
101
+ cloud the CLI creates `<app>-theme` (step "Bucket R2", before the configuration) and writes the name into the generated `wrangler.jsonc`; in local,
102
+ `wrangler dev` simulates it. That is why **every** cloud installation requires R2 to be enabled on the account.
103
+
104
+ **No product Worker receives the `ADMIN_TOKEN`** (the step refuses, and the tests check it): Chat, Widgets and Consultas talk to the
105
+ Core through the service route (the Core's `SERVICE_TOKEN` = the product's `CORE_SERVICE_TOKEN`).
106
+
107
+ ## What it asks
108
+ 1. **License** — Opera Source Code key (`osc1.…`) or Envato purchase code.
109
+ 2. **App name** → becomes the resource `slug` (`meu-chat-auth`, `meu-chat-identity`…) and the suggested bundle id
110
+ (`com.empresa.app`, from the owner's e-mail domain; webmail → `com.<app>.app`; override with `--bundle-id`). Only Chat has a
111
+ bundle id (Widgets has no app; `--bundle-id` is ignored).
112
+ 3. **Your e-mail** → the Core's `OWNER_EMAIL` (whoever signs in with it becomes the panel owner).
113
+ 4. **Languages** (default all 4: pt, es, en, ar) → the Core's `settings.locales` (the 1st is the default; the app only shows these).
114
+ 5. **Style + primary color** — colored swatches in the terminal (button, bubbles, light and dark) with the SAME `buildTheme`
115
+ as the app; if the color lacks contrast, the CLI shows which shade it was corrected to. Goes to `overture.theme.json` and
116
+ to the Core's `settings.theme`.
117
+ 6. **Cloudflare account** (only if you have more than one).
118
+ 7. **Opera keys** (App ID, App Secret and callback secret) — or "pular, configuro depois" (in the panel → Chat → Chaves do
119
+ Opera; for Widgets: Widgets do site → Widgets → Conexão com o Opera e e-mail).
120
+ With `--target local` these are the keys of a **TEST app** and are mandatory: without them the CLI stops at the step "Chaves do app de
121
+ TESTE do Opera", explains how to create the test app in the Opera console and shows the `--resume` line.
122
+ 8. **Sending the code by e-mail** (Resend key) — or skip: the owner signs in through the **first-access link** printed at the end.
123
+
124
+ Then it shows the summary and asks for confirmation. With `--target local` questions 6 and 8 do not exist.
125
+
126
+ ## What each step does (cloud)
127
+ The table is Chat's (20 steps). Widgets also has 20: without R2 (step 9) and with the **widget build** (`node build.mjs`)
128
+ between the migrations and the deploys; the product Worker is `<app>-widgets` with the secrets from the products table above.
129
+
130
+ | # | step | what it does | idempotent because… |
131
+ |---|---|---|---|
132
+ | 1 | License | checks the Ed25519 signature offline; `POST /v1/licenses/activate` | same installation = same activation |
133
+ | 2 | Project files | downloads the templates through the activation (sha256), copies Core + product + `vendor/` | done once |
134
+ | 3 | Secrets | `MASTER_KEY`, `ADMIN_TOKEN`, `SERVICE_TOKEN` (read-only, Chat → Core) and `CHAT_SECRETS_KEY` (encrypts the keys the Chat panel stores) generated → `.overture/secrets.env` (0600) | never replaces one that exists |
135
+ | 4 | Dependencies | `pnpm install --frozen-lockfile` in the 4 projects | only redoes it if the lockfile changes |
136
+ | 5 | Cloudflare account | token (`CLOUDFLARE_API_TOKEN`) or `wrangler login` | — |
137
+ | 6 | workers.dev | discovers `<sub>.workers.dev` (without a token: from the 1st deploy) | — |
138
+ | 7–8 | D1 `<app>-identity`, `<app>-chat` | looks it up; creates it if missing | looks up first; **exists and isn't ours → stops** |
139
+ | 9 | R2 `<app>-media` | looks it up; creates it | same |
140
+ | 10 | Pages `<app>-admin` | looks it up; creates it (the real subdomain comes from Cloudflare) | same |
141
+ | 11 | Configuration | `wrangler.jsonc` with ids/URLs/vars, `app.json`, `eas.json`, `overture.json` | redoes only if something changed |
142
+ | 12–13 | Migrations | `wrangler d1 migrations apply --remote` | D1 keeps track of what was already applied |
143
+ | 14–15 | Workers | `wrangler deploy --secrets-file` (0600 file deleted right after). Core: `MASTER_KEY`, `ADMIN_TOKEN`, `SERVICE_TOKEN`. Chat: `CORE_SERVICE_TOKEN`, `SECRETS_KEY` (+ the Opera ones, if provided) — **Chat does not receive the `ADMIN_TOKEN`** | redoes only if config/secret changed |
144
+ | 16–17 | Panel | `vite build` with `VITE_AUTH_URL` and `wrangler pages deploy` | redoes only if the auth URL changed |
145
+ | 18 | Core | `PUT /v1/admin/settings` (name, theme, **languages**, product with the Chat server's `apiUrl`, panel CORS) and e-mail with code as the primary method | reads first; only writes what changed |
146
+ | 19 | First-access link | `POST /v1/admin/bootstrap-link` (ADMIN_TOKEN) → **single-use, 15 min** panel link, printed at the end (only the masked version in the on-disk log; never in the state) | always runs: each run generates a new link and invalidates the previous one |
147
+ | 20 | Sweep | no secret in a file that git would version | always runs |
148
+
149
+ Before creating a resource the CLI records the **intent** in the state: if it crashes between "created" and "saved", the resume
150
+ adopts the resource instead of reporting a conflict.
151
+
152
+ `--target local`: 1–4, Opera TEST app keys (stops with the path if missing), free ports (starting at 8871),
153
+ configuration + `.dev.vars` (the product API points to `https://chat.operasignal.com` and `https://api.operasignal.com` with the
154
+ TEST app), local D1s (identity and product), panel and web app builds (`expo export --clear`; Widgets: the widget build
155
+ instead), sweep, brings up Core Auth, API, panel and app (Widgets: the test page) through `scripts/dev-local.mjs` and
156
+ configures the Core. It keeps running until Ctrl+C. Afterwards: `pnpm dev` in the project folder.
157
+
158
+ **Widgets in local:** create the widget in the panel (Widgets do site → Widgets) with the domain `localhost:<test page
159
+ port>` and open `http://localhost:<port>/?w=<widget id>` — the page carries the real snippet
160
+ (`<script src="http://localhost:<api>/w.js" data-widget="wdg_…" async>`). Widgets e-mail goes to the Worker log
161
+ (`EMAIL_MODE=log`).
162
+
163
+ **Callbacks in local:** cloud Opera cannot reach the buyer's `localhost`, so **push and reports via callback**
164
+ do not arrive. To test them: `cloudflared tunnel --url http://localhost:<api port>` and set
165
+ `<tunnel URL>/v1/opera/callback` as the TEST app's callback in the Opera console — or deploy to the cloud. The rest
166
+ (login, conversations, messages, photos, panel) works without it. The CLI shows this at the end of the local installation.
167
+
168
+ **The package does NOT ship the Opera chat server:** from `vendor/opera-signal-475ec74/` (Chat) or `vendor/opera-signal-a2d9876/`
169
+ (Widgets: the SDK with the chat scope in the token) only `packages/` (SDK: chat, uikit, client, protocol, server-auth, callkit)
170
+ and `tsconfig.base.json` are shipped. `apps/` is never copied (`copyTemplates` refuses and the
171
+ tests check that the generated project has no `apps/chat` file).
172
+
173
+ ## Flags and variables
174
+
175
+ | flag | env | meaning |
176
+ |---|---|---|
177
+ | `chat` \| `widgets` \| `consultas` \| `status` \| `agenda` \| `sites` \| `starter` \| `link` \| `imoveis` \| `quiz` \| `helpcenter` \| `classificados` | | the product |
178
+ | `[pasta]` | | default: `./<name slug>` |
179
+ | `--target cloud\|local` | | default `cloud` |
180
+ | `--yes` / `-y` | | no questions (something missing → says which flag to pass) |
181
+ | `--dry-run` | | shows the plan (every command and call) **without creating anything**, not even the folder |
182
+ | `--resume [pasta]` | | continues where it stopped (reads `.overture/`) |
183
+ | `--lang pt\|es\|en` | `OVERTURE_LANG`, `LANG` | installer language (Arabic still falls back to English) |
184
+ | `--log <arquivo>` | | color-free copy of the output |
185
+ | `--license <chave>` | `OVERTURE_LICENSE` | `osc1.…` key |
186
+ | `--purchase-code <código>` | `ENVATO_PURCHASE_CODE` | Envato |
187
+ | `--license-server <url>` | `OVERTURE_LICENSE_SERVER` | default `https://api.operasourcecode.com` |
188
+ | `--templates <pasta>` | `OVERTURE_TEMPLATES` | use a templates folder instead of the download (development) |
189
+ | `--name`, `--owner-email`, `--languages`, `--style`, `--primary`, `--bundle-id` | | the answers |
190
+ | `--account-id <id>` | `CLOUDFLARE_ACCOUNT_ID` | Cloudflare account |
191
+ | | `CLOUDFLARE_API_TOKEN` | token (without it, uses `wrangler login`) |
192
+ | `--opera-app-id <app_…>` | `OPERA_APP_SECRET`, `OPERA_CALLBACK_SECRET` | Opera keys (secret never by flag); in local, from a TEST app |
193
+ | `--skip-opera` | | configure later |
194
+ | `--email-from <remetente>` | `RESEND_API_KEY` | code e-mail (without `--email-from`, uses `<App> <login@owner's domain>`) |
195
+ | `--skip-email` | | configure later |
196
+ | `--status-domain <host>` | | Status: the page's own domain (Custom Domain + `PUBLIC_URL`) |
197
+ | `--short-domain <host>` | | Link: own short domain (Custom Domain + `PUBLIC_URL`) |
198
+ | `--site-domain <host>` | | Classificados: site domain (Custom Domain + `PUBLIC_URL`; SEO lives on it) |
199
+ | `--sample-data` / `--no-sample-data` | | Quiz: import the sample questions |
200
+ | `--workers-paid` / `--no-workers-paid` | | Link: has the paid Workers plan (click queue) |
201
+ | | `CF_API_TOKEN`, `CF_ZONE_ID`, `SAFE_BROWSING_KEY` | Link: customer domains (Cloudflare for SaaS) and Google Safe Browsing (optional) |
202
+ | | `TURNSTILE_SECRET` | Sites: contact captcha (optional) |
203
+ | `--no-serve` | | local: installs, configures and stops |
204
+ | `--provider simulated` | `OVERTURE_PROVIDER=simulated` | **demo**: simulated Cloudflare (warns on screen; the resume stays simulated) |
205
+
206
+ Secrets only through environment variables or a hidden prompt — never by flag (it would end up in the shell history and in `ps`).
207
+
208
+ ## Resuming
209
+ Any failure ends with what happened, what to do and the exact command line:
210
+ ```
211
+ ✖ Sem conexão com a Cloudflare.
212
+ O que fazer: Confira a internet e --resume.
213
+ Para continuar de onde parou: npx create-overture --resume meu-chat
214
+ ```
215
+ The state lives in `meu-chat/.overture/install.json` (no secrets). Running the original command again also resumes.
216
+ Changed an answer (e.g. `--opera-app-id`)? Only the affected steps run again.
217
+
218
+ ## What stays in the buyer's project
219
+ ```
220
+ overture.json the choices (versioned, no secrets)
221
+ overture.theme.json the theme
222
+ .overture/ state, log, license (0600) and secrets.env (0600) — outside git
223
+ overture-core/… overture-chat/… (or overture-widgets/…) vendor/… the templates (same paths as the repository)
224
+ scripts/dev-local.mjs pnpm dev (local only)
225
+ ```
226
+
227
+ ## Resend is no longer mandatory (first-access link)
228
+ In the cloud the Core runs with real delivery (`DELIVERY_MODE=log` would return the code in the response and **anyone
229
+ could sign in as any e-mail**). Without an e-mail provider, the owner signs in through the **first-access link** the CLI prints at the
230
+ end (`POST /v1/admin/bootstrap-link`: single use, 15 min, becomes panel owner). Expired? Run the command again — it only
231
+ does what is missing and generates another link. APP users can only sign in once the buyer enables a provider (Resend in the
232
+ panel → Formas de entrar, or run again with `RESEND_API_KEY` and `--email-from`). Local uses `log` (the code appears on screen)
233
+ and also prints the link.
234
+
235
+ ## Configure later from the panel
236
+ - **Opera keys** skipped → panel → **Chat → Chaves do Opera** (App ID, app secret, callback secret, "Testar
237
+ conexão" and the exact callback URL). They are stored encrypted in Chat's D1 and take precedence over the Worker secrets.
238
+ - **Push** (FCM/APNs) → panel → **Chat → Push** (with a test push and the latest deliveries).
239
+ - **Widgets**: the widget itself (colors, greeting, hours, **allowed domains**, who answers, calls) and the snippet →
240
+ panel → **Widgets do site → Widgets**; Turnstile (captcha) and Widgets push also through the panel or the Worker secrets.
241
+
242
+ ## Cloudflare token
243
+ Create it at https://dash.cloudflare.com/profile/api-tokens with: Account · Workers Scripts · Edit; D1 · Edit; Workers R2
244
+ Storage · Edit; Cloudflare Pages · Edit; Account Settings · Read; User · User Details · Read. Or `npx wrangler login`.
245
+
246
+ ## Costs the buyer will incur (no numbers here — they change; see the official pages)
247
+ - **Cloudflare Workers** (the 2 Workers: Core Auth + the product's): https://developers.cloudflare.com/workers/platform/pricing/
248
+ - **D1** (2 databases): https://developers.cloudflare.com/d1/platform/pricing/
249
+ - **R2** (every installation: the Core's `<app>-theme`; + `<app>-media` on Chat, `<app>-sites-files` on Sites and `<app>-link-media` on Link; enabling R2 requires a payment method even on the free tier): https://developers.cloudflare.com/r2/pricing/
250
+ - **Pages** (the panel): https://developers.cloudflare.com/pages/functions/pricing/ and https://www.cloudflare.com/plans/developer-platform/
251
+ - **Opera Signal** (chat, calls): the table in the Opera console/site (operasignal.com) — Opera pricing is the owner's decision.
252
+ - **Resend** (code e-mail): https://resend.com/pricing
253
+ - **Expo EAS** (cloud app build, optional): https://expo.dev/pricing
254
+ - **Stores:** Apple Developer Program https://developer.apple.com/support/enrollment/ · Google Play https://support.google.com/googleplay/android-developer/answer/6112435
255
+
256
+ ## Development
257
+ ```sh
258
+ export PATH=$HOME/.nvm/versions/node/v22.23.2/bin:$PATH
259
+ pnpm install
260
+ pnpm typecheck && pnpm test # tsc + Vitest (226 tests: license, generation, plan, simulated/real provider with fakes, first-access link, local without Opera, the 12 products, theme R2 and Core fonts, accountUrl)
261
+ pnpm build && pnpm e2e # Chat: LOCAL end-to-end with 2 Chrome instances (writes docs/terminal-local.txt and docs/e2e/01–07)
262
+ pnpm build && pnpm e2e:widgets # Widgets: installs local, creates the widget, the test page loads w.js and the visitor opens the conversation (docs/e2e/08–09)
263
+ pnpm build && pnpm e2e:consultas # Consultas: installs local, identical payment secrets on Core and Consultas, cron, the owner creates a professional + service in the panel (docs/e2e/10)
264
+ pnpm build && pnpm e2e:status # Status: no Opera, ports 23200–23299, the owner signs in through the link, sees "Status", creates a monitor, the cron checks and the page responds (docs/e2e/11)
265
+ pnpm build && pnpm e2e:agenda # Agenda: identical payment secrets, cron, the owner sees "Agenda", creates a service in the panel and a customer books through the public page (docs/e2e/12, 16)
266
+ pnpm build && pnpm e2e:sites # Sites: R2 FILES, the owner sees "Site", creates the home page, publishes to local R2 and the site responds (docs/e2e/13)
267
+ pnpm build && pnpm e2e:starter # Starter: web app with EXPO_PUBLIC_WEB_URL, the owner sees "Starter" and changes the Pro free trial in the panel (docs/e2e/14)
268
+ pnpm build && pnpm e2e:link # Link: no queue in local, theme alias, the owner sees "Link", changes the Free limit; a short link redirects (docs/e2e/15)
269
+ pnpm build && pnpm e2e:imoveis # Imóveis: the owner sees "Imóveis", the portal site and fonts are served by the Worker (docs/e2e/17)
270
+ pnpm build && pnpm e2e:quiz # Quiz: sample questions imported in local, the owner sees "Quiz" and the questions (docs/e2e/18)
271
+ pnpm build && pnpm e2e:helpcenter # Help Center: widget compiled first, /help, /widget.js, panel "Central de ajuda" (docs/e2e/19)
272
+ pnpm build && pnpm e2e:classificados # Classificados: the INSTALADOR.md checks through the CLI, post-installation steps, "Classificados" (docs/e2e/20)
273
+ ```
274
+ The e2e is 100% local: it brings up Opera's chat itself from the copy in `vendor/` (only in OUR repository) and passes the CLI the
275
+ INTERNAL variable `OVERTURE_INTERNAL_OPERA_CHAT_URL` (not documented to the buyer) + its own test app keys —
276
+ it never touches the published Opera. Each e2e runs in an ISOLATED state (`os.tmpdir()/overture-e2e-<product>-<pid>`, or `E2E_STATE_DIR`) and only deletes that folder:
277
+ the Opera chat in the tests uses its own config with absolute paths and `--persist-to` there — never the `.wrangler` of
278
+ `vendor/` (shared with other sessions). The status/agenda/sites/starter/link e2e pass `OVERTURE_INTERNAL_PORT_BASE=23200` (also internal) so local uses the range
279
+ 23200–23299 (inspectors starting at 23250).
280
+ ```sh
281
+ node tools/fake-license-server.mjs --port 8899 --templates ../../.. # FAKE license server
282
+ node tools/fake-license-server.mjs --mint chat # a TEST license (or --mint widgets / consultas)
283
+ ```
284
+ - `src/theme/vendor/{color,tokens}.ts` are faithful copies of `overture-core/app/react-native/packages/theme/src` (the test
285
+ checks it). Changed there → copy again.
286
+ - The store contract is in `LICENSE-API.md`.
@@ -0,0 +1,205 @@
1
+ #!/usr/bin/env node
2
+ // Starts the WHOLE Overture project on this computer (generated by create-overture --target local):
3
+ // Core Auth (wrangler dev, local D1, DELIVERY_MODE=log) · product API · panel and web app (static server).
4
+ // Widgets: in place of the app, a TEST PAGE with the snippet (http://localhost:<site>/?w=<widget id>).
5
+ // Status: no app and no Opera — the Status Worker is the public page and the cron (checks) is called every minute.
6
+ // The Opera chat is the CLOUD one, with the buyer's Opera TEST app (keys in the API's .dev.vars, outside git).
7
+ // Opera callbacks (push, reports) do not reach localhost: use a tunnel (cloudflared tunnel --url …) or the cloud.
8
+ // Usage: pnpm dev (or node scripts/dev-local.mjs). Ctrl+C brings everything down.
9
+ // Node only (20+): no dependency besides the wrangler already present in each Worker.
10
+ import { spawn } from 'node:child_process'
11
+ import { existsSync, readFileSync, statSync } from 'node:fs'
12
+ import { createServer } from 'node:http'
13
+ import { createServer as netServer } from 'node:net'
14
+ import { dirname, extname, join, normalize, resolve } from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+
17
+ const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
18
+ const L = JSON.parse(readFileSync(join(ROOT, 'overture.json'), 'utf8'))
19
+ const ports = L.local?.ports
20
+ if (!ports) {
21
+ console.error('overture.json sem "local.ports": rode o create-overture com --target local primeiro.')
22
+ process.exit(1)
23
+ }
24
+ // what changes per product (same as create-overture's ProductSpec): the product Worker, how to tell it is up, statics
25
+ const PRODUCT = {
26
+ chat: { api: 'overture-chat/api/workers', state: 'chat', name: 'chat-api', health: '/v1/config', statics: { admin: 'overture-core/web/react/dist', app: 'overture-chat/app/react-native/dist' } },
27
+ widgets: { api: 'overture-widgets/api/workers', state: 'widgets', name: 'widgets-api', health: '/', statics: { admin: 'overture-core/web/react/dist' }, site: true },
28
+ // cron: wrangler dev does not run cron by itself — it starts with --test-scheduled and this script calls /__scheduled every minute
29
+ // (Consultas: reminders, expired locks; Core: retries of payment callbacks)
30
+ consultas: { api: 'overture-consultas/api/workers', state: 'consultas', name: 'consultas-api', health: '/', statics: { admin: 'overture-core/web/react/dist', app: 'overture-consultas/app/react-native/dist' }, cron: '* * * * *' },
31
+ // Status: no Opera and no app; the Worker is the public page and the cron runs the checks (every minute, here too)
32
+ status: { api: 'overture-status/api/workers', state: 'status', name: 'status-api', health: '/v1/health', statics: { admin: 'overture-core/web/react/dist' }, cron: '* * * * *', noOpera: true },
33
+ // Agenda: no Opera; web app + the public booking page ('site' port); reminders/locks cron; SIMULATED payment
34
+ // Starter: no Opera; customer web app (Expo export); hourly cron (free trial, plan change, period)
35
+ starter: { api: 'overture-starter/api/workers', state: 'starter', name: 'starter-api', health: '/', statics: { admin: 'overture-core/web/react/dist', app: 'overture-starter/app/react-native/dist' }, cron: '0 * * * *', noOpera: true },
36
+ // Link: no Opera; web app; hourly cron (at minute 17); locally the clicks go straight to D1 (no queue)
37
+ link: { api: 'overture-link/api/workers', state: 'link', name: 'link-api', health: '/', statics: { admin: 'overture-core/web/react/dist', app: 'overture-link/app/react-native/dist' }, cron: '17 * * * *', noOpera: true },
38
+ // Imóveis: the portal site is the Worker itself; advertiser web app; hourly cron (at minute 17)
39
+ imoveis: { api: 'overture-imoveis/api/workers', state: 'imoveis', name: 'imoveis-api', health: '/v1/health', statics: { admin: 'overture-core/web/react/dist', app: 'overture-imoveis/app/react-native/dist' }, cron: '17 * * * *', noOpera: true },
40
+ // Quiz: the game on the web; hourly cron
41
+ quiz: { api: 'overture-quiz/api/workers', state: 'quiz', name: 'quiz-api', health: '/', statics: { admin: 'overture-core/web/react/dist', app: 'overture-quiz/app/react-native/dist' }, cron: '0 * * * *', noOpera: true },
42
+ // Help Center: the help center (/help) and the widget (/widget.js) are served by the Worker; cron every minute (SLA)
43
+ helpcenter: { api: 'overture-helpcenter/api/workers', state: 'helpcenter', name: 'helpcenter-api', health: '/', statics: { admin: 'overture-core/web/react/dist' }, cron: '* * * * *', noOpera: true },
44
+ // Classificados: the SEO site is the Worker itself; web app; cron every 5 min (expired, featured)
45
+ classificados: { api: 'overture-classificados/api/workers', state: 'classificados', name: 'classificados-api', health: '/v1/health', statics: { admin: 'overture-core/web/react/dist', app: 'overture-classificados/app/react-native/dist' }, cron: '*/5 * * * *', noOpera: true },
46
+ // Delivery: customer and courier web app; cron every minute (orders with overdue payment), as in Consultas
47
+ delivery: { api: 'overture-delivery/api/workers', state: 'delivery', name: 'delivery-api', health: '/', statics: { admin: 'overture-core/web/react/dist', app: 'overture-delivery/app/react-native/dist' }, cron: '* * * * *', noOpera: true },
48
+ // Cardápio: no app; the table page is the Worker itself (/m/…); dining-room Durable Object (wrangler dev simulates it); cron every minute
49
+ cardapio: { api: 'overture-cardapio/api/workers', state: 'cardapio', name: 'cardapio-api', health: '/health', statics: { admin: 'overture-core/web/react/dist' }, cron: '* * * * *', noOpera: true },
50
+ // Shop: the storefront is the Worker itself; customer web app; cron every minute (stock locks, overdue charges)
51
+ shop: { api: 'overture-shop/api/workers', state: 'shop', name: 'shop-api', health: '/v1/health', statics: { admin: 'overture-core/web/react/dist', app: 'overture-shop/app/react-native/dist' }, cron: '* * * * *', noOpera: true },
52
+ // Faturas: public links are served by the Worker; company web app; hourly cron (at minute 23)
53
+ faturas: { api: 'overture-faturas/api/workers', state: 'faturas', name: 'faturas-api', health: '/', statics: { admin: 'overture-core/web/react/dist', app: 'overture-faturas/app/react-native/dist' }, cron: '23 * * * *', noOpera: true },
54
+ // Cursos: videos in local R2 (signed links); student web app; hourly cron (at minute 17)
55
+ cursos: { api: 'overture-cursos/api/workers', state: 'cursos', name: 'cursos-api', health: '/v1/health', statics: { admin: 'overture-core/web/react/dist', app: 'overture-cursos/app/react-native/dist' }, cron: '17 * * * *', noOpera: true },
56
+ // Sites: no Opera and no cron; the Worker serves the published site (local R2) and /_a/* (Workers Assets)
57
+ sites: { api: 'overture-sites/api/workers', state: 'sites', name: 'sites-api', health: '/_a/site.css', statics: { admin: 'overture-core/web/react/dist' }, noOpera: true },
58
+ agenda: { api: 'overture-agenda/api/workers', state: 'agenda', name: 'agenda-api', health: '/', statics: { admin: 'overture-core/web/react/dist', app: 'overture-agenda/app/react-native/dist', site: 'overture-agenda/web/embed/dist' }, cron: '* * * * *', noOpera: true },
59
+ }[L.product ?? 'chat']
60
+ if (!PRODUCT) {
61
+ console.error(`produto desconhecido no overture.json: ${L.product}`)
62
+ process.exit(1)
63
+ }
64
+ const STATE = join(ROOT, '.overture/local')
65
+ const CORE = join(ROOT, 'overture-core/api/workers')
66
+ const API = join(ROOT, PRODUCT.api)
67
+ const bin = (dir) => join(dir, 'node_modules/.bin', process.platform === 'win32' ? 'wrangler.cmd' : 'wrangler')
68
+ const URLS = Object.fromEntries(['auth', 'api', 'admin', 'app', 'site'].filter((k) => ports[k]).map((k) => [k, `http://localhost:${ports[k]}`]))
69
+
70
+ const procs = []
71
+ const servers = []
72
+ let stopping = false
73
+ async function stop(code = 0) {
74
+ if (stopping) return
75
+ stopping = true
76
+ for (const p of procs) try { p.kill('SIGTERM') } catch {}
77
+ for (const s of servers) try { s.close() } catch {}
78
+ await new Promise((r) => setTimeout(r, 1500))
79
+ for (const p of procs) try { p.kill('SIGKILL') } catch {}
80
+ process.exit(code)
81
+ }
82
+ process.on('SIGINT', () => stop(0))
83
+ process.on('SIGTERM', () => stop(0))
84
+
85
+ const free = (port, host) => new Promise((r) => {
86
+ const s = netServer().once('error', (e) => r(host === '::1' && (e.code === 'EADDRNOTAVAIL' || e.code === 'EAFNOSUPPORT'))).once('listening', () => s.close(() => r(true)))
87
+ s.listen(port, host)
88
+ })
89
+ for (const [k, p] of Object.entries(ports)) {
90
+ if (!p) continue
91
+ if (!(await free(p, '127.0.0.1')) || !(await free(p, '::1'))) {
92
+ console.error(`OVERTURE_ERROR port_busy ${p} (${k})`)
93
+ process.exit(2)
94
+ }
95
+ }
96
+
97
+ function start(name, cmd, args, cwd) {
98
+ const p = spawn(cmd, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, CI: '1', WRANGLER_SEND_METRICS: 'false' }, shell: process.platform === 'win32' })
99
+ let log = ''
100
+ const onData = (d) => {
101
+ log = (log + d).slice(-20000)
102
+ if (process.env.OVERTURE_VERBOSE) process.stdout.write(`[${name}] ${d}`)
103
+ }
104
+ p.stdout.on('data', onData)
105
+ p.stderr.on('data', onData)
106
+ p.on('exit', (code) => {
107
+ if (stopping) return
108
+ console.error(`OVERTURE_ERROR local_start_failed ${name} (saída ${code})\n${log.split('\n').slice(-25).join('\n')}`)
109
+ stop(1)
110
+ })
111
+ p.tail = () => log.split('\n').slice(-25).join('\n')
112
+ procs.push(p)
113
+ return p
114
+ }
115
+ const devArgs = (port, insp, persist) => ['dev', '--port', String(port), '--inspector-port', String(insp), '--persist-to', persist, ...(PRODUCT.cron ? ['--test-scheduled'] : []), '--show-interactive-dev-session=false']
116
+
117
+ // 1. Core Auth
118
+ const core = start('core-auth', bin(CORE), devArgs(ports.auth, ports.inspAuth, join(STATE, 'state/core')), CORE)
119
+ // 2. product API (Chat/Widgets/Consultas: talks to the cloud Opera chat; Status: no Opera)
120
+ const api = start(PRODUCT.name, bin(API), devArgs(ports.api, ports.inspApi, join(STATE, `state/${PRODUCT.state}`)), API)
121
+
122
+ // 3. panel and app: static files with fallback to index.html (SPA)
123
+ const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.ttf': 'font/ttf', '.woff2': 'font/woff2', '.map': 'application/json' }
124
+ function serve(root, port) {
125
+ const s = createServer((req, res) => {
126
+ const path = decodeURIComponent(new URL(req.url, 'http://x').pathname)
127
+ let file = normalize(join(root, path))
128
+ if (!file.startsWith(root) || !existsSync(file) || statSync(file).isDirectory()) file = join(root, 'index.html')
129
+ res.setHeader('content-type', MIME[extname(file)] ?? 'application/octet-stream')
130
+ res.setHeader('cache-control', 'no-store')
131
+ res.end(readFileSync(file))
132
+ })
133
+ s.listen(port)
134
+ servers.push(s)
135
+ }
136
+ for (const [k, rel] of Object.entries(PRODUCT.statics)) {
137
+ const dist = join(ROOT, rel)
138
+ if (!existsSync(join(dist, 'index.html'))) {
139
+ console.error(`OVERTURE_ERROR local_start_failed ${k === 'admin' ? 'painel' : k} (falta o build em ${dist})`)
140
+ await stop(1)
141
+ }
142
+ serve(dist, ports[k])
143
+ }
144
+
145
+ // 4. Widgets: the test page with the real SNIPPET (<script src=".../w.js" data-widget="wdg_…" async>). The widget only
146
+ // opens if this page's domain (localhost:<port>) is in the widget's "Domains" in the panel.
147
+ if (PRODUCT.site) {
148
+ const esc = (v) => String(v).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c])
149
+ const s = createServer((req, res) => {
150
+ const u = new URL(req.url, URLS.site)
151
+ if (u.pathname !== '/') { res.statusCode = 404; return res.end('not found') }
152
+ const w = u.searchParams.get('w') ?? ''
153
+ const ok = /^wdg_[0-9A-Za-z]+$/.test(w)
154
+ const snippet = ok ? `<script src="${URLS.api}/w.js" data-widget="${w}" async></script>` : ''
155
+ res.setHeader('content-type', 'text/html; charset=utf-8')
156
+ res.setHeader('cache-control', 'no-store')
157
+ res.end(`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${esc(L.appName)} · widget test</title>
158
+ <style>body{font:16px/1.5 system-ui,sans-serif;max-width:640px;margin:48px auto;padding:0 16px;color:#222}code{background:#f2f2f2;padding:2px 4px;border-radius:4px;word-break:break-all}</style></head><body>
159
+ <h1>${esc(L.appName)}</h1>
160
+ ${ok ? `<p>Widget <code>${esc(w)}</code> (snippet below / abaixo):</p><p><code>${esc(snippet)}</code></p>` : `<p>Create a widget in the panel (Website widgets → Widgets) with the domain <code>${esc(u.host)}</code> and open <code>${esc(URLS.site)}/?w=&lt;widget id&gt;</code>.</p><p>Crie um widget no painel (Widgets do site → Widgets) com o domínio <code>${esc(u.host)}</code> e abra <code>${esc(URLS.site)}/?w=&lt;id do widget&gt;</code>.</p>`}
161
+ ${snippet}
162
+ </body></html>`)
163
+ })
164
+ s.listen(ports.site)
165
+ servers.push(s)
166
+ }
167
+
168
+ async function waitHttp(name, url, p, ms = 120_000) {
169
+ const t0 = Date.now()
170
+ while (Date.now() - t0 < ms) {
171
+ try { if ((await fetch(url)).status < 500) return } catch {}
172
+ await new Promise((r) => setTimeout(r, 400))
173
+ }
174
+ console.error(`OVERTURE_ERROR local_start_failed ${name} (não respondeu em ${url})\n${p?.tail?.() ?? ''}`)
175
+ await stop(1)
176
+ }
177
+ await Promise.all([
178
+ waitHttp('core-auth', `${URLS.auth}/.well-known/jwks.json`, core),
179
+ waitHttp(PRODUCT.name, `${URLS.api}${PRODUCT.health}`, api),
180
+ waitHttp('painel', `${URLS.admin}/`),
181
+ ...(URLS.app ? [waitHttp('app', `${URLS.app}/`)] : []),
182
+ ...(URLS.site ? [waitHttp('site', `${URLS.site}/`)] : []),
183
+ ])
184
+ // 5. local cron: every minute, the same thing Cloudflare would do in the cloud (Core + product API)
185
+ if (PRODUCT.cron) {
186
+ const cron = encodeURIComponent(PRODUCT.cron).replace(/%20/g, '+')
187
+ const tick = async () => {
188
+ for (const base of [URLS.auth, URLS.api]) {
189
+ try {
190
+ const r = await fetch(`${base}/__scheduled?cron=${cron}`)
191
+ if (!r.ok && process.env.OVERTURE_VERBOSE) console.log(`[cron] ${base} → ${r.status}`)
192
+ } catch {}
193
+ }
194
+ }
195
+ // "* * * * *" = every minute; "0 * * * *" (Starter) = hourly
196
+ setInterval(tick, PRODUCT.cron.startsWith('* ') ? 60_000 : /^\*\/(\d+) /.test(PRODUCT.cron) ? Number(/^\*\/(\d+) /.exec(PRODUCT.cron)[1]) * 60_000 : 3_600_000).unref?.()
197
+ // the 1st one right away: locks/reminders that expired while everything was stopped
198
+ void tick()
199
+ }
200
+ console.log(`OVERTURE_READY ${JSON.stringify(URLS)}`)
201
+ if (!process.env.OVERTURE_CHILD && PRODUCT.noOpera) {
202
+ console.log(`\n ${L.appName} — tudo de pé:\n painel ${URLS.admin}\n${URLS.app ? ` app ${URLS.app}\n` : ''}${URLS.site && !PRODUCT.site ? ` reservas ${URLS.site}\n` : ''} ${L.product === 'status' ? 'página' : L.product === 'sites' ? 'site ' : 'api '} ${URLS.api}/\n login ${URLS.auth}\n\n ${PRODUCT.cron ? (PRODUCT.cron.startsWith('* ') ? 'O cron roda a cada minuto; o' : PRODUCT.cron.startsWith('*/') ? 'O cron roda a cada ' + PRODUCT.cron.slice(2).split(' ')[0] + ' min; o' : 'O cron roda de hora em hora; o') : 'O'}s avisos só vão para o log (NOTIFY_MODE=log).\n\n Ctrl+C derruba tudo.`)
203
+ } else if (!process.env.OVERTURE_CHILD) {
204
+ console.log(`\n ${L.appName} — tudo de pé:\n painel ${URLS.admin}\n ${URLS.app ? `app ${URLS.app}` : `teste ${URLS.site}/?w=<id do widget>`}\n login ${URLS.auth}\n api ${URLS.api}\n chat ${L.urls?.opera ?? 'https://chat.operasignal.com'} (Opera na nuvem, app de TESTE)\n\n Callbacks do Opera (push, denúncias) não chegam aqui: cloudflared tunnel --url ${URLS.api}\n e ponha <URL do túnel>/v1/opera/callback no seu app de TESTE no console do Opera.\n\n Ctrl+C derruba tudo.`)
205
+ }