@protobase/cli 0.26.8 → 0.27.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.
Files changed (34) hide show
  1. package/dist/build/deploy-bundle.js +2 -1
  2. package/dist/{package.js → cli/package.js} +1 -1
  3. package/dist/main.js +2 -0
  4. package/dist/mobile/api-origin.js +34 -0
  5. package/dist/mobile/arguments.js +16 -0
  6. package/dist/mobile/cap-run-args.js +22 -0
  7. package/dist/mobile/capacitor-config.js +25 -0
  8. package/dist/mobile/capacitor.js +17 -0
  9. package/dist/mobile/child-env.js +26 -0
  10. package/dist/mobile/child-process.js +17 -0
  11. package/dist/mobile/fingerprint.js +12 -0
  12. package/dist/mobile/generate.js +20 -0
  13. package/dist/mobile/info-plist.js +11 -0
  14. package/dist/mobile/installed-package.js +20 -0
  15. package/dist/mobile/load-project.js +25 -0
  16. package/dist/mobile/mobile-config.js +26 -0
  17. package/dist/mobile/package.js +13 -0
  18. package/dist/mobile/pinned-packages.js +27 -0
  19. package/dist/mobile/platform.js +4 -0
  20. package/dist/mobile/register.js +33 -0
  21. package/dist/mobile/run.js +84 -0
  22. package/dist/mobile/web-part.js +54 -0
  23. package/dist/mobile/workspace.js +42 -0
  24. package/dist/project/project-admin.js +1 -0
  25. package/dist/project/protobase-folder.js +5 -0
  26. package/dist/project/service-worker.js +1 -1
  27. package/dist/version/version.js +1 -1
  28. package/package.json +6 -6
  29. package/skills/protobase/SKILL.md +1 -0
  30. package/skills/protobase/references/guides/mobile-app.md +64 -0
  31. package/skills/protobase/references/reference/api.md +1 -1
  32. package/skills/protobase/references/reference/auth.md +6 -1
  33. package/skills/protobase/references/reference/cli.md +16 -1
  34. package/skills/protobase/references/reference/ui-config.md +1 -1
@@ -8,6 +8,7 @@ import { buildTheme } from "./theme.js";
8
8
  import { shellForBuild, shellManifestFile } from "./shell.js";
9
9
  import { checkUi } from "./ui-check.js";
10
10
  import { checkViews } from "./view-check.js";
11
+ import { protobaseFolder } from "../project/protobase-folder.js";
11
12
  import { existsSync } from "node:fs";
12
13
  import path from "node:path";
13
14
  import { cp, readFile, rm, writeFile } from "node:fs/promises";
@@ -60,7 +61,7 @@ const buildDeployBundle = async ({ projectDir, outDir, bun, extensions = [], onW
60
61
  projectDir,
61
62
  publicDir,
62
63
  extensions,
63
- ignore: [outDir]
64
+ ignore: [outDir, path.join(projectDir, protobaseFolder)]
64
65
  });
65
66
  for (const warning of await buildTheme({
66
67
  projectDir,
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.26.8";
2
+ var version = "0.27.0";
3
3
  //#endregion
4
4
  export { version };
package/dist/main.js CHANGED
@@ -20,6 +20,7 @@ import { loadWorkerBundle, startWorker } from "./worker/start-worker.js";
20
20
  import { registerOrganizations } from "./organizations/register.js";
21
21
  import { registerFiles } from "./files/register.js";
22
22
  import { registerMigration } from "./migration/register.js";
23
+ import { registerMobile } from "./mobile/register.js";
23
24
  import { registerSkill } from "./skill/register.js";
24
25
  import { registerImport } from "./supabase/register.js";
25
26
  import { registerToken, registerUsers } from "./users/register.js";
@@ -132,6 +133,7 @@ registerMigration(program);
132
133
  registerFiles(program);
133
134
  registerSkill(program);
134
135
  registerImport(program);
136
+ registerMobile(program);
135
137
  const run = (argv) => program.parseAsync(argv).catch((error) => {
136
138
  process.stderr.write(`error: ${error.message}\n`);
137
139
  process.exitCode = 1;
@@ -0,0 +1,34 @@
1
+ //#region src/mobile/api-origin.ts
2
+ const loopback = ["localhost", "127.0.0.1"];
3
+ const httpHosts = {
4
+ ios: [...loopback, "[::1]"],
5
+ android: [...loopback, "10.0.2.2"]
6
+ };
7
+ /**
8
+ * The server the app calls: `--api` when given, else the auth issuer (`baseURL`). It must be an http or https origin
9
+ * with nothing after it; plain http only to this machine, or the Android emulator's host, since anyone on the network
10
+ * between could read or change what it sends.
11
+ */
12
+ const apiUrl = (given, issuer, platform) => {
13
+ const value = given ?? issuer;
14
+ const what = given === void 0 ? `The auth issuer (baseURL) "${value}"` : `--api ${given}`;
15
+ if (value === void 0) throw new Error("This project has no auth issuer (baseURL) for the app to call: pass --api https://…");
16
+ if (!URL.canParse(value)) throw new Error(`${what} is not a URL such as https://shop.example.com`);
17
+ const url = new URL(value);
18
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(`${what} must be an http or https URL`);
19
+ if (url.username || url.password || url.pathname !== "/" || url.search || url.hash || value.endsWith("?") || value.endsWith("#")) throw new Error(`${what} must be an origin such as https://shop.example.com, without a user, path, query or fragment`);
20
+ if (url.protocol === "http:" && !httpHosts[platform].includes(url.hostname)) throw new Error(`${what} uses plain http to ${url.hostname}: plain http is only for a server on this machine (${httpHosts[platform].join(", ")}); any other server needs https`);
21
+ return url;
22
+ };
23
+ /** What the app must allow to reach `url`: plain http, and on Android mixed content for a host that is not loopback. */
24
+ const httpAllowances = (url) => ({
25
+ cleartext: url.protocol === "http:",
26
+ mixedContent: url.hostname === "10.0.2.2"
27
+ });
28
+ /** The port `adb reverse` forwards for an Android app calling `url` on this machine, `undefined` for any other. */
29
+ const forwardedPort = (url, platform) => {
30
+ if (platform !== "android" || !loopback.includes(url.hostname)) return void 0;
31
+ return Number(url.port || (url.protocol === "https:" ? 443 : 80));
32
+ };
33
+ //#endregion
34
+ export { apiUrl, forwardedPort, httpAllowances };
@@ -0,0 +1,16 @@
1
+ import { platforms } from "./platform.js";
2
+ import { InvalidArgumentError } from "commander";
3
+ //#region src/mobile/arguments.ts
4
+ /** The `<platform>` argument: ios or android. */
5
+ const parsePlatform = (value) => {
6
+ if (platforms.includes(value)) return value;
7
+ throw new InvalidArgumentError("expected ios or android");
8
+ };
9
+ /** A `--port` option: digits only, from 1 to 65535, as a number, so no other text reaches a URL or Capacitor. */
10
+ const parsePort = (value) => {
11
+ const number = /^\d{1,5}$/.test(value) ? Number(value) : 0;
12
+ if (number < 1 || number > 65535) throw new InvalidArgumentError("expected a port from 1 to 65535");
13
+ return number;
14
+ };
15
+ //#endregion
16
+ export { parsePlatform, parsePort };
@@ -0,0 +1,22 @@
1
+ import { forwardedPort } from "./api-origin.js";
2
+ //#region src/mobile/cap-run-args.ts
3
+ /** The arguments of `cap run`, after the native project was generated and synced. */
4
+ const capRunArgs = ({ platform, target, url, live }) => {
5
+ const port = forwardedPort(url, platform);
6
+ return [
7
+ "run",
8
+ platform,
9
+ "--no-sync",
10
+ ...target ? ["--target", target] : [],
11
+ ...port === void 0 ? [] : ["--forwardPorts", `${port}:${port}`],
12
+ ...live === void 0 ? [] : [
13
+ "--live-reload",
14
+ "--host",
15
+ "localhost",
16
+ "--port",
17
+ String(live)
18
+ ]
19
+ ];
20
+ };
21
+ //#endregion
22
+ export { capRunArgs };
@@ -0,0 +1,25 @@
1
+ import path from "node:path";
2
+ import { rm, writeFile } from "node:fs/promises";
3
+ //#region src/mobile/capacitor-config.ts
4
+ /**
5
+ * The app's `capacitor.config.json`, every key it sets named here. It never sets `server.url`, the hostname or the
6
+ * schemes (the API's CORS list names Capacitor's default origins), `plugins` (so CapacitorHttp and CapacitorCookies
7
+ * stay off) or WebView debugging (on in debug builds only). The fingerprint goes in the user agent, which a live
8
+ * update cannot change.
9
+ */
10
+ const capacitorConfig = ({ appId, appName, fingerprint, plugins, allowances }) => ({
11
+ appId,
12
+ appName,
13
+ webDir: "web",
14
+ appendUserAgent: `ProtobaseNative/${fingerprint}`,
15
+ includePlugins: plugins,
16
+ ...allowances.cleartext && { server: { cleartext: true } },
17
+ ...allowances.mixedContent && { android: { allowMixedContent: true } }
18
+ });
19
+ /** Writes the config into the workspace `dir`, removing the `.ts` and `.js` configs Capacitor would read instead. */
20
+ const writeCapacitorConfig = async (dir, config) => {
21
+ await Promise.all(["capacitor.config.ts", "capacitor.config.js"].map((name) => rm(path.join(dir, name), { force: true })));
22
+ await writeFile(path.join(dir, "capacitor.config.json"), `${JSON.stringify(config, null, 2)}\n`);
23
+ };
24
+ //#endregion
25
+ export { capacitorConfig, writeCapacitorConfig };
@@ -0,0 +1,17 @@
1
+ import { installedPackage } from "./installed-package.js";
2
+ import path from "node:path";
3
+ //#region src/mobile/capacitor.ts
4
+ /**
5
+ * Runs the workspace's own Capacitor CLI, read from `<ws>/node_modules/@capacitor/cli` by path, so never one of the
6
+ * project's or another found further up, with Node and the given environment.
7
+ */
8
+ const capacitorRunner = (ws, env, run) => async (args) => {
9
+ const { name, bin } = installedPackage(ws, "@capacitor/cli");
10
+ if (name !== "@capacitor/cli" || !bin?.cap) throw new Error(`${path.join(ws, "node_modules", "@capacitor/cli")} is ${name}, not Capacitor's CLI`);
11
+ await run("node", [path.join(ws, "node_modules", "@capacitor", "cli", bin.cap), ...args], {
12
+ cwd: ws,
13
+ env
14
+ });
15
+ };
16
+ //#endregion
17
+ export { capacitorRunner };
@@ -0,0 +1,26 @@
1
+ import { readFileSync, readdirSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { parseEnv } from "node:util";
4
+ //#region src/mobile/child-env.ts
5
+ const isFile = (file) => {
6
+ try {
7
+ return statSync(file).isFile();
8
+ } catch (error) {
9
+ if (error.code === "ENOENT") return false;
10
+ throw error;
11
+ }
12
+ };
13
+ /** The files in `dir` Bun may have loaded env from: every `.env*`, in any letter case, that is a file once links are followed. */
14
+ const projectEnvFiles = (dir) => readdirSync(dir).filter((name) => name.toLowerCase().startsWith(".env")).map((name) => path.join(dir, name)).filter(isFile);
15
+ /** The keys `files` set, without a leading byte order mark, which Bun strips and `parseEnv` keeps. */
16
+ const envFileKeys = (files) => new Set(files.flatMap((file) => Object.keys(parseEnv(readFileSync(file, "utf8").replace(/^/, "")))));
17
+ /**
18
+ * The environment for npm and Capacitor: `env` without `keys`, even where the shell set one of them, and with `CI`,
19
+ * without which Capacitor opts the user into its telemetry from an interactive terminal and sends the app id.
20
+ */
21
+ const childEnv = (env, keys) => ({
22
+ ...Object.fromEntries(Object.entries(env).filter(([key, value]) => value !== void 0 && !keys.has(key))),
23
+ CI: "true"
24
+ });
25
+ //#endregion
26
+ export { childEnv, envFileKeys, projectEnvFiles };
@@ -0,0 +1,17 @@
1
+ import { spawn } from "node:child_process";
2
+ //#region src/mobile/child-process.ts
3
+ /**
4
+ * Runs `command` with `args` as given, never through a shell, in `cwd` with exactly `env`: without it the child would
5
+ * get the CLI's whole environment, with the project's secrets.
6
+ */
7
+ const runChild = (command, args, { cwd, env }, spawn$1 = spawn) => new Promise((resolve, reject) => {
8
+ const child = spawn$1(command, args, {
9
+ cwd,
10
+ env,
11
+ stdio: "inherit"
12
+ });
13
+ child.on("error", (error) => reject(error.code === "ENOENT" ? /* @__PURE__ */ new Error(`${command} is not installed, or not on PATH`) : error));
14
+ child.on("close", (status) => status === 0 ? resolve() : reject(/* @__PURE__ */ new Error(`\`${command} ${args.join(" ")}\` exited with status ${status}`)));
15
+ });
16
+ //#endregion
17
+ export { runChild };
@@ -0,0 +1,12 @@
1
+ import { createHash } from "node:crypto";
2
+ //#region src/mobile/fingerprint.ts
3
+ /** Names the app's native code: the same for two builds only when they compile in the same native packages. */
4
+ const nativeFingerprint = ({ mobile, plugins }) => {
5
+ const sorted = [...plugins].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
6
+ return createHash("sha256").update(JSON.stringify({
7
+ mobile,
8
+ plugins: sorted
9
+ })).digest("hex").slice(0, 16);
10
+ };
11
+ //#endregion
12
+ export { nativeFingerprint };
@@ -0,0 +1,20 @@
1
+ import { withLocalNetworking } from "./info-plist.js";
2
+ import path from "node:path";
3
+ import { readFile, rm, writeFile } from "node:fs/promises";
4
+ //#region src/mobile/generate.ts
5
+ const infoPlist = (ws) => path.join(ws, "ios", "App", "App", "Info.plist");
6
+ /**
7
+ * Generates the platform's native project in the workspace from its capacitor.config.json and app files, replacing
8
+ * the last one: it is never edited by hand. An iOS app calling the API over plain http may reach local addresses.
9
+ */
10
+ const generatePlatform = async (ws, platform, { cleartext }, cap) => {
11
+ await rm(path.join(ws, platform), {
12
+ recursive: true,
13
+ force: true
14
+ });
15
+ await cap(["add", platform]);
16
+ if (platform !== "ios" || !cleartext) return;
17
+ await writeFile(infoPlist(ws), withLocalNetworking(await readFile(infoPlist(ws), "utf8")));
18
+ };
19
+ //#endregion
20
+ export { generatePlatform };
@@ -0,0 +1,11 @@
1
+ //#region src/mobile/info-plist.ts
2
+ const end = "</dict>\n</plist>";
3
+ /** The app's Info.plist allowing plain http to local addresses only (`NSAllowsLocalNetworking`), never to the internet. */
4
+ const withLocalNetworking = (plist) => {
5
+ if (plist.includes("<key>NSAppTransportSecurity</key>")) throw new Error("Info.plist already has NSAppTransportSecurity");
6
+ const at = plist.lastIndexOf(end);
7
+ if (at < 0) throw new Error("Info.plist does not end with </dict></plist>");
8
+ return `${plist.slice(0, at)}\t<key>NSAppTransportSecurity</key>\n\t<dict>\n\t\t<key>NSAllowsLocalNetworking</key>\n\t\t<true/>\n\t</dict>\n${plist.slice(at)}`;
9
+ };
10
+ //#endregion
11
+ export { withLocalNetworking };
@@ -0,0 +1,20 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ //#region src/mobile/installed-package.ts
4
+ /**
5
+ * The name and version of the package installed as `name` in the workspace `dir`, read from
6
+ * `<dir>/node_modules/<name>/package.json` by path, never by Node's lookup, which would go on into the project's own
7
+ * node_modules. Its `name` is the package's own, which differs from `name` for an npm alias.
8
+ */
9
+ const installedPackage = (dir, name) => {
10
+ const file = path.join(dir, "node_modules", name, "package.json");
11
+ if (!existsSync(file)) throw new Error(`${name} is not installed in ${dir}: run the command again to install it`);
12
+ const { name: own, version, bin } = JSON.parse(readFileSync(file, "utf8"));
13
+ return {
14
+ name: own,
15
+ version,
16
+ ...bin && { bin }
17
+ };
18
+ };
19
+ //#endregion
20
+ export { installedPackage };
@@ -0,0 +1,25 @@
1
+ import { loadNearestEnvFile } from "../dev/env.js";
2
+ import { importProjectFile } from "../project/import-project-file.js";
3
+ import { noMobileSection } from "./mobile-config.js";
4
+ import { existsSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { mergeConfig } from "@protobase/server";
7
+ //#region src/mobile/load-project.ts
8
+ const configOf = async (file) => (await importProjectFile(file)).default ?? {};
9
+ /**
10
+ * What a mobile build needs of the project in `dir`, merged as `protobase dev` merges it after the configs of
11
+ * `extensions`: its mobile section, unchecked, and its auth. The project's .env is loaded first, as other commands do.
12
+ */
13
+ const loadMobileProject = async (dir, extensions) => {
14
+ loadNearestEnvFile(dir);
15
+ const file = path.join(dir, "protobase.config.ts");
16
+ if (!existsSync(file)) throw new Error(noMobileSection);
17
+ const extended = await Promise.all(extensions.flatMap((extension) => extension.config ? [configOf(extension.config)] : []));
18
+ const { mobile, auth } = mergeConfig(...extended, await configOf(file));
19
+ return {
20
+ mobile,
21
+ auth
22
+ };
23
+ };
24
+ //#endregion
25
+ export { loadMobileProject };
@@ -0,0 +1,26 @@
1
+ import { pinnedProblem } from "./pinned-packages.js";
2
+ //#region src/mobile/mobile-config.ts
3
+ const noMobileSection = "This project has no mobile section: add `mobile: { appId: 'com.example.app' }` to the default export of protobase.config.ts";
4
+ const appIdPattern = /^[a-zA-Z][\w]*(?:\.[a-zA-Z][\w]*)+$/;
5
+ const unauthenticated = /^(?:http:|git:|git\+http:)/i;
6
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7
+ /** The project's `mobile` section, checked: an error says what to add or fix. */
8
+ const checkMobileConfig = (value) => {
9
+ if (value === void 0) throw new Error(noMobileSection);
10
+ if (!isRecord(value)) throw new Error("mobile in protobase.config.ts must be an object such as { appId: 'com.example.app' }");
11
+ const { appId, plugins } = value;
12
+ if (typeof appId !== "string" || !appIdPattern.test(appId.toLowerCase())) throw new Error(`mobile.appId must be a reverse-DNS id such as com.example.app: at least two parts separated by dots, each starting with a letter and holding only letters, digits and underscores, not ${JSON.stringify(appId)}`);
13
+ if (plugins === void 0) return { appId };
14
+ if (!isRecord(plugins) || Object.values(plugins).some((spec) => typeof spec !== "string")) throw new Error("mobile.plugins must map each plugin's npm name to a version range, such as { '@capacitor/camera': '^8.0.0' }");
15
+ for (const [name, spec] of Object.entries(plugins)) {
16
+ const problem = pinnedProblem(name);
17
+ if (problem) throw new Error(problem);
18
+ if (unauthenticated.test(spec)) throw new Error(`mobile.plugins installs ${name} from ${spec}, over a connection that is not secure: use a version range, https or git+https`);
19
+ }
20
+ return {
21
+ appId,
22
+ plugins
23
+ };
24
+ };
25
+ //#endregion
26
+ export { checkMobileConfig, noMobileSection };
@@ -0,0 +1,13 @@
1
+ //#region ../mobile/package.json
2
+ var name = "@protobase/mobile";
3
+ var dependencies = {
4
+ "@capacitor/android": "8.5.3",
5
+ "@capacitor/app": "8.1.2",
6
+ "@capacitor/cli": "8.5.3",
7
+ "@capacitor/core": "8.5.3",
8
+ "@capacitor/ios": "8.5.3",
9
+ "@capacitor/splash-screen": "8.0.2",
10
+ "@capawesome/capacitor-live-update": "8.7.1"
11
+ };
12
+ //#endregion
13
+ export { dependencies, name };
@@ -0,0 +1,27 @@
1
+ import { installedPackage } from "./installed-package.js";
2
+ import { dependencies, name } from "./package.js";
3
+ //#region src/mobile/pinned-packages.ts
4
+ /**
5
+ * The packages @protobase/mobile pins, itself included, which `mobile.plugins` may neither pin again nor compile into
6
+ * the app. Read from its package.json and inlined into the CLI's build, so the CLI carries the list of the
7
+ * @protobase/mobile of its own version, the one it installs.
8
+ */
9
+ const pinnedPackages = /* @__PURE__ */ new Set([name, ...Object.keys(dependencies)]);
10
+ const liveUpdate = "@capawesome/capacitor-live-update";
11
+ /** Why the plugin `key`, a package that is or names `name`, may not be listed; `undefined` when it may. */
12
+ const pinnedProblem = (key, name = key) => {
13
+ if (name === liveUpdate) return `mobile.plugins lists ${key}, ${liveUpdate}: live updates come with Protobase's updater, which does not enable the plugin yet; remove it from mobile.plugins`;
14
+ if (pinnedPackages.has(name)) return `mobile.plugins lists ${key}, which ${name === key ? "comes" : `installs ${name}, which comes`} with Protobase at a fixed version: remove it from mobile.plugins`;
15
+ };
16
+ /**
17
+ * Checks the installed packages of the configured plugins `keys` in the workspace `dir`: one that is a pinned package
18
+ * under another name, such as an npm alias or a `file:` spec, is refused before Capacitor compiles it in.
19
+ */
20
+ const checkInstalledPlugins = (dir, keys) => {
21
+ for (const key of keys) {
22
+ const problem = pinnedProblem(key, installedPackage(dir, key).name);
23
+ if (problem) throw new Error(problem);
24
+ }
25
+ };
26
+ //#endregion
27
+ export { checkInstalledPlugins, pinnedPackages, pinnedProblem };
@@ -0,0 +1,4 @@
1
+ //#region src/mobile/platform.ts
2
+ const platforms = ["ios", "android"];
3
+ //#endregion
4
+ export { platforms };
@@ -0,0 +1,33 @@
1
+ import { resolveExtensions } from "../project/extensions.js";
2
+ import { parsePlatform, parsePort } from "./arguments.js";
3
+ //#region src/mobile/register.ts
4
+ const out = (text) => process.stdout.write(text);
5
+ const collect = (value, previous) => [...previous, value];
6
+ const registerMobile = (program) => {
7
+ const mobile = program.command("mobile").description("Build the project in the current directory as an iOS or Android app, from the mobile section of its protobase.config.ts");
8
+ const api = "--api <url>";
9
+ const apiHelp = "the server the app calls (default: the auth issuer, the project's baseURL)";
10
+ const extend = "merge the protobase.config.ts and protobase.ui.tsx in this folder before the project's, repeatable";
11
+ mobile.command("run").description("Generate the native project and run the app in a simulator, an emulator or on a device").argument("<platform>", "ios or android", parsePlatform).option(api, apiHelp).option("--target <id>", "the device or simulator to run on (default: Capacitor asks)").option("--live", "open the running protobase dev instead of the app's own files, reloading as you save", false).option("--port <port>", "the port of protobase dev, for --live", parsePort, 5173).option("--extend <dir>", extend, collect, []).action(async (chosen, opts) => {
12
+ const { mobileRun } = await import("./run.js");
13
+ await mobileRun({
14
+ projectDir: process.cwd(),
15
+ platform: chosen,
16
+ extensions: resolveExtensions(opts.extend),
17
+ ...opts.api !== void 0 && { api: opts.api },
18
+ ...opts.target && { target: opts.target },
19
+ ...opts.live && { live: opts.port }
20
+ }, out);
21
+ });
22
+ mobile.command("open").description("Generate the native project and open it in Xcode or Android Studio").argument("<platform>", "ios or android", parsePlatform).option(api, apiHelp).option("--extend <dir>", extend, collect, []).action(async (chosen, opts) => {
23
+ const { mobileOpen } = await import("./run.js");
24
+ await mobileOpen({
25
+ projectDir: process.cwd(),
26
+ platform: chosen,
27
+ extensions: resolveExtensions(opts.extend),
28
+ ...opts.api !== void 0 && { api: opts.api }
29
+ }, out);
30
+ });
31
+ };
32
+ //#endregion
33
+ export { registerMobile };
@@ -0,0 +1,84 @@
1
+ import { apiUrl, httpAllowances } from "./api-origin.js";
2
+ import { capRunArgs } from "./cap-run-args.js";
3
+ import { installedPackage } from "./installed-package.js";
4
+ import { capacitorRunner } from "./capacitor.js";
5
+ import { buildWebPart, placeholderWebPart } from "./web-part.js";
6
+ import { capacitorConfig, writeCapacitorConfig } from "./capacitor-config.js";
7
+ import { childEnv, envFileKeys, projectEnvFiles } from "./child-env.js";
8
+ import { runChild } from "./child-process.js";
9
+ import { nativeFingerprint } from "./fingerprint.js";
10
+ import { generatePlatform } from "./generate.js";
11
+ import { checkInstalledPlugins } from "./pinned-packages.js";
12
+ import { checkMobileConfig } from "./mobile-config.js";
13
+ import { loadMobileProject } from "./load-project.js";
14
+ import { mobileSpec, prepareWorkspace, workspaceDir, workspacePackageJson } from "./workspace.js";
15
+ import path from "node:path";
16
+ import { defaultAppName } from "@protobase/server";
17
+ //#region src/mobile/run.ts
18
+ const prepare = async ({ projectDir, platform, api, extensions, live }, { run = runChild, build }) => {
19
+ const env = childEnv({ ...process.env }, envFileKeys(projectEnvFiles(projectDir)));
20
+ if (live !== void 0 && api !== void 0) throw new Error("--live opens protobase dev, which serves the API itself: leave out --api");
21
+ const project = await loadMobileProject(projectDir, extensions);
22
+ const mobile = checkMobileConfig(project.mobile);
23
+ const url = live === void 0 ? apiUrl(api, project.auth?.issuer, platform) : new URL(`http://localhost:${live}`);
24
+ const allowances = httpAllowances(url);
25
+ const ws = workspaceDir(projectDir);
26
+ const plugins = Object.keys(mobile.plugins ?? {});
27
+ await prepareWorkspace(ws, workspacePackageJson({
28
+ mobileSpec: mobileSpec(),
29
+ ...mobile.plugins && { plugins: mobile.plugins }
30
+ }), (command, args) => run(command, args, {
31
+ cwd: ws,
32
+ env
33
+ }));
34
+ checkInstalledPlugins(ws, plugins);
35
+ if (live === void 0) await buildWebPart({
36
+ projectDir,
37
+ ws,
38
+ extensions,
39
+ apiOrigin: url.origin,
40
+ ...build && { build },
41
+ onWarning: (message) => process.stderr.write(`warning: ${message}\n`)
42
+ });
43
+ else await placeholderWebPart(ws);
44
+ const fingerprint = nativeFingerprint({
45
+ mobile: installedPackage(ws, "@protobase/mobile").version,
46
+ plugins: plugins.map((key) => [key, installedPackage(ws, key).version])
47
+ });
48
+ const appName = project.auth?.appName ?? defaultAppName;
49
+ await writeCapacitorConfig(ws, capacitorConfig({
50
+ appId: mobile.appId,
51
+ appName,
52
+ fingerprint,
53
+ plugins,
54
+ allowances
55
+ }));
56
+ const cap = capacitorRunner(ws, env, run);
57
+ await generatePlatform(ws, platform, allowances, cap);
58
+ return {
59
+ ws,
60
+ url,
61
+ fingerprint,
62
+ cap
63
+ };
64
+ };
65
+ const summary = (projectDir, { ws, url, fingerprint }) => `workspace ${path.relative(projectDir, ws)}, api ${url.origin}, native fingerprint ${fingerprint}\n`;
66
+ /** `protobase mobile run`: generates the native project and runs the app on a simulator, emulator or device. */
67
+ const mobileRun = async (input, out, deps = {}) => {
68
+ const prepared = await prepare(input, deps);
69
+ out(summary(input.projectDir, prepared));
70
+ await prepared.cap(capRunArgs({
71
+ platform: input.platform,
72
+ url: prepared.url,
73
+ ...input.target && { target: input.target },
74
+ ...input.live !== void 0 && { live: input.live }
75
+ }));
76
+ };
77
+ /** `protobase mobile open`: generates the native project and opens it in Xcode or Android Studio. */
78
+ const mobileOpen = async (input, out, deps = {}) => {
79
+ const prepared = await prepare(input, deps);
80
+ out(summary(input.projectDir, prepared));
81
+ await prepared.cap(["open", input.platform]);
82
+ };
83
+ //#endregion
84
+ export { mobileOpen, mobileRun };
@@ -0,0 +1,54 @@
1
+ import { bundleLayout } from "../bundle/manifest.js";
2
+ import { buildDeployBundle } from "../build/deploy-bundle.js";
3
+ import path from "node:path";
4
+ import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
5
+ import { apiOriginMeta } from "@protobase/schema/internal";
6
+ const escapeAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
7
+ /** The page naming the API origin the shell calls, in the `<meta>` tag the shell reads (see `apiOriginMeta`). */
8
+ const withApiOrigin = (html, origin) => {
9
+ const at = html.indexOf("</head>");
10
+ if (at < 0) throw new Error("The shell's index.html has no </head> to name the API origin in");
11
+ return `${html.slice(0, at)}<meta name="${apiOriginMeta}" content="${escapeAttribute(origin)}">${html.slice(at)}`;
12
+ };
13
+ /**
14
+ * The app's files: the deploy bundle's `public/` (the shell, the project's UI plugins, theme and favicon), its
15
+ * index.html naming the API origin. The bundle is built beside it and removed, so its server config module and
16
+ * packages never sit where Capacitor copies from.
17
+ */
18
+ const buildWebPart = async ({ projectDir, ws, extensions, apiOrigin, build = buildDeployBundle, onWarning }) => {
19
+ const bundle = path.join(ws, "bundle");
20
+ const web = path.join(ws, "web");
21
+ await rm(bundle, {
22
+ recursive: true,
23
+ force: true
24
+ });
25
+ await build({
26
+ projectDir,
27
+ outDir: bundle,
28
+ extensions,
29
+ ...onWarning && { onWarning }
30
+ });
31
+ await rm(web, {
32
+ recursive: true,
33
+ force: true
34
+ });
35
+ await cp(path.join(bundle, bundleLayout.public), web, { recursive: true });
36
+ await rm(bundle, {
37
+ recursive: true,
38
+ force: true
39
+ });
40
+ const index = path.join(web, bundleLayout.spa);
41
+ await writeFile(index, withApiOrigin(await readFile(index, "utf8"), apiOrigin));
42
+ };
43
+ /** A stand-in for the app's files with `--live`, where the app opens `protobase dev` and never shows them. */
44
+ const placeholderWebPart = async (ws) => {
45
+ const web = path.join(ws, "web");
46
+ await rm(web, {
47
+ recursive: true,
48
+ force: true
49
+ });
50
+ await mkdir(web, { recursive: true });
51
+ await writeFile(path.join(web, bundleLayout.spa), "<!doctype html><title>protobase dev</title>\n");
52
+ };
53
+ //#endregion
54
+ export { buildWebPart, placeholderWebPart, withApiOrigin };
@@ -0,0 +1,42 @@
1
+ import { protobaseVersion } from "../version/version.js";
2
+ import { protobaseFolder } from "../project/protobase-folder.js";
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
6
+ import { fileURLToPath } from "node:url";
7
+ //#region src/mobile/workspace.ts
8
+ /** Where the mobile build lives in a project: npm's install of @protobase/mobile, the app's files and native projects. */
9
+ const workspaceDir = (projectDir) => path.join(projectDir, protobaseFolder, "mobile");
10
+ const fromSource = path.extname(import.meta.url) === ".ts";
11
+ /** The @protobase/mobile to install: the CLI's own version, or this repository's package when the CLI runs from source. */
12
+ const mobileSpec = (source = fromSource) => source ? `file:${fileURLToPath(new URL("../../../mobile", import.meta.url))}` : protobaseVersion;
13
+ /** The workspace's package.json: @protobase/mobile and the project's extra plugins. */
14
+ const workspacePackageJson = ({ mobileSpec, plugins = {} }) => ({
15
+ private: true,
16
+ dependencies: {
17
+ "@protobase/mobile": mobileSpec,
18
+ ...plugins
19
+ }
20
+ });
21
+ /**
22
+ * Writes the workspace in `dir`, ignored by git, and installs its packages with npm when its package.json changed or
23
+ * one of them is missing, as after an install that failed. `--install-links` copies a `file:` package and puts its
24
+ * dependencies at the workspace's root, where Capacitor looks for them.
25
+ */
26
+ const prepareWorkspace = async (dir, packageJson, run) => {
27
+ await mkdir(dir, { recursive: true });
28
+ await writeFile(path.join(dir, ".gitignore"), "*\n");
29
+ const file = path.join(dir, "package.json");
30
+ const content = `${JSON.stringify(packageJson, null, 2)}\n`;
31
+ const changed = !existsSync(file) || await readFile(file, "utf8") !== content;
32
+ const missing = Object.keys(packageJson.dependencies).some((name) => !existsSync(path.join(dir, "node_modules", name, "package.json")));
33
+ if (changed) await writeFile(file, content);
34
+ if (changed || missing) await run("npm", [
35
+ "install",
36
+ "--install-links",
37
+ "--no-audit",
38
+ "--no-fund"
39
+ ]);
40
+ };
41
+ //#endregion
42
+ export { mobileSpec, prepareWorkspace, workspaceDir, workspacePackageJson };
@@ -25,6 +25,7 @@ const projectAdmin = (project, config, db, ui, reporter, upgradeWebSocket) => {
25
25
  ...project.events && { events: project.events },
26
26
  ...project.history && { history: project.history },
27
27
  ...project.webhooks && { webhooks: project.webhooks },
28
+ ...project.mobile && { mobile: project.mobile },
28
29
  jobs: own,
29
30
  subscriptions,
30
31
  ...ui && {
@@ -0,0 +1,5 @@
1
+ //#region src/project/protobase-folder.ts
2
+ /** The folder in a project where Protobase keeps what it generates, such as the mobile workspace; never the app's own files. */
3
+ const protobaseFolder = ".protobase";
4
+ //#endregion
5
+ export { protobaseFolder };
@@ -15,7 +15,7 @@ const serviceWorker = () => ({
15
15
  order: "post",
16
16
  handler: () => [{
17
17
  tag: "script",
18
- children: `if ('serviceWorker' in navigator) navigator.serviceWorker.register('/${serviceWorkerFile}')`,
18
+ children: `if ('serviceWorker' in navigator && !window.Capacitor) navigator.serviceWorker.register('/${serviceWorkerFile}')`,
19
19
  injectTo: "body"
20
20
  }]
21
21
  },
@@ -1,4 +1,4 @@
1
- import { version } from "../package.js";
1
+ import { version } from "../cli/package.js";
2
2
  //#region src/version/version.ts
3
3
  const protobaseVersion = version;
4
4
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.26.8",
3
+ "version": "0.27.0",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -35,11 +35,11 @@
35
35
  "dependencies": {
36
36
  "@hono/node-server": "^2.1.3",
37
37
  "@hono/vite-dev-server": "^0.26.1",
38
- "@protobase/layout": "0.26.8",
39
- "@protobase/query": "0.26.8",
40
- "@protobase/schema": "0.26.8",
41
- "@protobase/server": "0.26.8",
42
- "@protobase/ui": "0.26.8",
38
+ "@protobase/layout": "0.27.0",
39
+ "@protobase/query": "0.27.0",
40
+ "@protobase/schema": "0.27.0",
41
+ "@protobase/server": "0.27.0",
42
+ "@protobase/ui": "0.27.0",
43
43
  "@react-email/render": "^2.1.0",
44
44
  "@scalar/hono-api-reference": "^0.12.10",
45
45
  "@tailwindcss/vite": "^4.3.3",
@@ -53,6 +53,7 @@ Guides:
53
53
  - When letting users save a list as Excel or CSV → read [Exporting a list](references/guides/export-a-list.md)
54
54
  - When importing records from a spreadsheet → read [Importing records from a spreadsheet](references/guides/import-records.md)
55
55
  - When replacing a resource's create form with a page of your own → read [A create page of your own](references/guides/create-page.md)
56
+ - When running the app on iOS or Android → read [A mobile app](references/guides/mobile-app.md)
56
57
 
57
58
  Reference:
58
59
 
@@ -0,0 +1,64 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/guides/mobile-app.md: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # A mobile app
4
+
5
+ Run a Protobase app on iOS and Android from a mobile section in its config, without setting up Capacitor yourself.
6
+
7
+ A Protobase app runs as an iOS or Android app with nothing more than a `mobile` section in its `protobase.config.ts`. `protobase mobile` wraps the app in [Capacitor](https://capacitorjs.com): the app's shell, its UI plugins, theme and favicon open from files on the device, and the app calls your server's API.
8
+
9
+ Signing in from the app is not supported yet: until then the app shows that it cannot reach the server's sign-in, while its API calls go through.
10
+
11
+ ## 1. Install the tools
12
+
13
+ - **iOS**, on a Mac: Xcode, with a simulator.
14
+ - **Android**: the Android SDK, with an emulator, and JDK 21.
15
+
16
+ Set their variables, such as `ANDROID_HOME` and `JAVA_HOME`, in your shell, not in the project's `.env`: the commands hand npm and Capacitor no variable named in any of the project's `.env*` files, even when the shell sets a variable of the same name, since those files hold the app's secrets.
17
+
18
+ ## 2. Add a mobile section
19
+
20
+ ```ts
21
+ // protobase.config.ts
22
+ export default defineConfig({
23
+ // ...
24
+ mobile: {
25
+ appId: 'com.example.shop',
26
+ plugins: { '@capacitor/camera': '^8.0.0' },
27
+ },
28
+ })
29
+ ```
30
+
31
+ - `appId` is the app's id in reverse-DNS form: at least two parts separated by dots, each starting with a letter and holding only letters, digits and underscores.
32
+ - `plugins`, optional, are extra native [Capacitor plugins](https://capacitorjs.com/docs/plugins), npm name to version. Capacitor itself, `@capacitor/app`, `@capacitor/splash-screen` and `@capawesome/capacitor-live-update` come with Protobase at fixed versions and cannot be listed. A plugin runs native code with the app's rights, and one that writes files, such as `@capacitor/filesystem`, lets a script that got into the page point the app at files it wrote (with Capacitor's own `WebView.setServerBasePath`), so list only plugins the app needs.
33
+
34
+ With a mobile section, the API answers the app's origins, `capacitor://localhost` on iOS and `https://localhost` on Android, through [CORS](../reference/api.md#cors)). Apps without one get no new dependency, and `protobase build` and `protobase dev` work as before.
35
+
36
+ ## 3. Run it
37
+
38
+ ```sh
39
+ protobase mobile run android
40
+ protobase mobile run ios
41
+ ```
42
+
43
+ The first run installs Capacitor into `.protobase/mobile/`, which ignores itself in git. Every run builds the app's files as [`protobase build`](../reference/cli.md#build)) does and generates the native project from your config again, so never edit the projects in `.protobase/mobile/` by hand. Your own package.json gains nothing.
44
+
45
+ The app calls the server at the project's auth `baseURL`; pass `--api https://shop.example.com` for another one. Plain http is only for a server on this machine (`localhost`) or, on the Android emulator, its host `10.0.2.2`; any other server needs https. An Android phone on USB reaches a server on `localhost` through a forwarded port; an iPhone needs an https server. The app's UI plugins load from the device only when the server serves a built bundle (`protobase serve dist`): against `protobase dev`, use `--live`.
46
+
47
+ `--target <id>` picks the simulator, emulator or device; without it Capacitor asks.
48
+
49
+ ## 4. Live reload
50
+
51
+ ```sh
52
+ protobase dev
53
+ protobase mobile run android --live
54
+ ```
55
+
56
+ With `--live` the app opens the running `protobase dev` instead of its own files, so it reloads as you save. `--port` names the dev server's port, 5173 by default.
57
+
58
+ ## 5. Open the native project
59
+
60
+ ```sh
61
+ protobase mobile open ios
62
+ ```
63
+
64
+ opens the generated project in Xcode, or Android Studio for `android`. To run on an iPhone, pick a signing team in Xcode's Signing & Capabilities.
@@ -184,7 +184,7 @@ Real login is [Better Auth](auth.md)). Lower level:
184
184
 
185
185
  ## CORS
186
186
 
187
- The API sends no CORS headers until it has something to allow: other websites in `options.cors` (a list of origins, or `'*'` for any), which defaults to `PROTOBASE_CORS_ORIGINS` (`*` or comma separated origins), or other [origins of the app](auth.md#several-origins)), which are always allowed.
187
+ The API sends no CORS headers until it has something to allow: other websites in `options.cors` (a list of origins, or `'*'` for any), which defaults to `PROTOBASE_CORS_ORIGINS` (`*` or comma separated http and https origins), other [origins of the app](auth.md#several-origins)), which are always allowed, or a [mobile section](../guides/mobile-app.md)), which allows the app's Capacitor origins, `capacitor://localhost` and `https://localhost`. `PROTOBASE_CORS_ORIGINS` refuses other schemes at startup.
188
188
 
189
189
  - It covers `/api/*` but Better Auth's `/api/auth/*`, which checks origins itself, and [API functions](../guides/api-functions.md)) with a `cors` of their own, and supabase-js's sign-in at [`/auth/v1`](auth.md#supabase-js-and-supabasessr)).
190
190
  - An allowed origin gets `Access-Control-Allow-Origin` with its name and `Vary: Origin`, or `*` with `'*'`. No credentials: browser code calls the API with a bearer token.
@@ -75,7 +75,7 @@ The columns Better Auth needs that the table lacks, filled from what the other s
75
75
  | `TRUSTED_ORIGINS` | extra comma separated origins; a dev tunnel needs its exact host here, such as `https://my-tunnel.trycloudflare.com`, since no wildcard is trusted |
76
76
  | `PROTOBASE_ORIGINS` | the other origins the app is served on, comma separated, passed by the platform; see [Several origins](#several-origins) |
77
77
  | `PROTOBASE_PASSKEY_DOMAIN` | the host new [passkeys](#passkeys) are made for, passed by the platform; default the host of `BETTER_AUTH_URL` |
78
- | `PROTOBASE_CORS_ORIGINS` | other websites whose browser code may call the API, `*` or comma separated origins, passed by the platform; see [CORS](api.md#cors)) |
78
+ | `PROTOBASE_CORS_ORIGINS` | other websites whose browser code may call the API, `*` or comma separated http and https origins, passed by the platform; see [CORS](api.md#cors)) |
79
79
  | `PROTOBASE_SMTP_URL`, `PROTOBASE_MAIL_FROM` | the mail server and sender for [password reset](#password-reset), [emailed sign-in codes](#emailed-sign-in-codes), emailed [two-factor](#two-factor-authentication) codes and [open sign-up](#open-sign-up), passed by the platform; all four are off without them |
80
80
  | `PROTOBASE_APP_NAME` | the app's name, passed by the platform: the default of `appName` |
81
81
  | `PROTOBASE_SIGN_IN_ISSUER`, `PROTOBASE_SIGN_IN_CLIENT_ID`, `PROTOBASE_SIGN_IN_CLIENT_SECRET` | the [platform sign-in provider](#platform-sign-in-provider) for people who have an account, passed by the platform; off without them. `PROTOBASE_SIGN_IN_PROVIDER` and `PROTOBASE_SIGN_IN_NAME` are optional |
@@ -188,6 +188,7 @@ People add passkeys (Face ID, Touch ID, Windows Hello, a phone or a security key
188
188
 
189
189
  - A passkey is made for the app's passkey domain, its RP ID: the host of `BETTER_AUTH_URL` (`admin.example.com`), or the host of one of its [other origins](#several-origins) set with `passkeyDomain` or `PROTOBASE_PASSKEY_DOMAIN`. For local development, `http://localhost` works.
190
190
  - Each passkey keeps the RP ID it was made for (`passkey.rp_id`), so changing the passkey domain breaks none. Passkeys made before Protobase kept it count for the host of `BETTER_AUTH_URL`, which they were made for; renaming that host breaks them. The column is new in 0.10: the server refuses to start until the [migration](#migrations) that adds it is applied.
191
+ - A passkey's answer, for adding a passkey or signing in, must name the origin of `BETTER_AUTH_URL` or one of the [other origins](#several-origins) exactly. An origin listed only in `TRUSTED_ORIGINS`, such as a dev tunnel, cannot use passkeys: list it as one of the other origins instead.
191
192
  - On an app with several origins, every passkey works on each of them through [Related Origin Requests](https://passkeys.dev/docs/advanced/related-origins/) (Chrome and Edge 128, Safari 18, Firefox 152; at most 5 registrable domains).
192
193
  - A browser asks for the passkeys of one RP ID at a time. When people have passkeys for more than one of the app's hosts, `GET /api/auth/status` lists them as `passkeyDomains`, the passkey domain first, and the sign-in page adds "Use a passkey made for {host}" for each of the others. `GET /api/auth/passkey/generate-authenticate-options?rpId=<host>` asks for one of them.
193
194
  - A passkey sign-in asks for no second step: the passkey is something you have and something you are or know.
@@ -450,6 +451,10 @@ Their tokens are verified against that app's keys at `<issuer>/api/auth/jwks`; a
450
451
  An app moving from Supabase keeps its `supabase.auth` calls and its `@supabase/ssr` session checks: the app serves GoTrue's endpoints at `/auth/v1`, over the same Better Auth sign-in, so `createClient(<the app's origin>, <publishable key>)` signs in, refreshes, reads the user and signs out as on Supabase.
451
452
 
452
453
  - `signInWithPassword`, `signInWithOtp` then `verifyOtp({ email, token, type: 'email' })`, `signInWithOAuth` with one of the app's [sign-in providers](#sign-in-with-github) (PKCE, as `@supabase/ssr` uses, or the implicit flow), `refreshSession`, `getUser`, `getClaims`, `updateUser({ password, data })` and `signOut` work. Each goes through Better Auth's own endpoint, with its rate limits and the [sign-in policy](#sign-in-policy).
454
+ - The implicit flow is for an https `redirect_to` only. For http, including localhost, and custom schemes, use PKCE: supabase-js `flowType: 'pkce'`; `@supabase/ssr` already uses it.
455
+ - The sign-in must start at `/auth/v1/authorize` in the same browser: `/auth/v1/callback` hands a code or a session only at the end of a provider sign-in started there.
456
+ - The browser keeps no Protobase session afterwards: the app holds its own.
457
+ - A wildcard pattern in `TRUSTED_ORIGINS` lets implicit-flow tokens go to any https host it matches.
453
458
  - Addresses are proved with the emailed 6-digit code, never a link. `signUp({ email, password, options: { data } })` needs [open sign-up](#open-sign-up) and mails a sign-up code; `verifyOtp({ email, token, type: 'signup' })` makes the account, with `data` in the [user metadata column](#an-existing-users-table), and signs in. Until then there is no account and `signUp` answers no user. `resetPasswordForEmail` mails a sign-in code; `verifyOtp` with `type: 'recovery'` signs in, and `updateUser({ password })` sets the new password.
454
459
  - The access token is ES256, valid for an hour, with Supabase's claims: `sub`, `role: authenticated`, `aud: authenticated`, `email`, `app_metadata`, `user_metadata`, `aal`, `session_id`, issued by `<baseURL>/auth/v1`. Its keys are at `/auth/v1/.well-known/jwks.json`. It is apart from the EdDSA token of [Tokens and roles](#tokens-and-roles): neither is accepted for the other.
455
460
  - The refresh token is the Better Auth session's token. Each refresh gives the session a new one, so a refresh token works once, and signing out, a ban or a revoked session ends it.
@@ -365,7 +365,7 @@ Serves the API of a bundle from `protobase build` and owns the process around it
365
365
  | `PROTOBASE_SIGN_IN_ISSUER`, `PROTOBASE_SIGN_IN_CLIENT_ID`, `PROTOBASE_SIGN_IN_CLIENT_SECRET` | an OpenID Connect provider people who have an account can sign in with; all three or none. `PROTOBASE_SIGN_IN_PROVIDER` and `PROTOBASE_SIGN_IN_NAME` are optional ([Platform sign-in provider](auth.md#platform-sign-in-provider))) |
366
366
  | `PROTOBASE_OPERATOR_ISSUER`, `PROTOBASE_OPERATOR_CLIENT_ID`, `PROTOBASE_OPERATOR_CLIENT_SECRET` | the OpenID Connect provider of the operator's staff, for [staff sign-in](auth.md#staff-sign-in)) as people of the app; all three or none. `PROTOBASE_OPERATOR_NAME` and `PROTOBASE_OPERATOR_GROUP` are optional ([Operator provider](auth.md#operator-provider))) |
367
367
  | `PROTOBASE_ORIGINS`, `PROTOBASE_PASSKEY_DOMAIN` | the other origins the app is served on, comma separated, and the host new passkeys are made for ([Several origins](auth.md#several-origins))) |
368
- | `PROTOBASE_CORS_ORIGINS` | other websites whose browser code may call the API, `*` or comma separated origins ([CORS](api.md#cors))) |
368
+ | `PROTOBASE_CORS_ORIGINS` | other websites whose browser code may call the API, `*` or comma separated http and https origins ([CORS](api.md#cors))) |
369
369
  | `PROTOBASE_ASSISTANT_URL`, `PROTOBASE_ASSISTANT_API_KEY`, `PROTOBASE_ASSISTANT_MODEL`, `PROTOBASE_ASSISTANT_BASE_URL` | the [assistant](assistant.md#which-backend)): a backend elsewhere, or the built-in one on OpenRouter or another OpenAI-compatible endpoint; without them there is none |
370
370
  | `PROTOBASE_RUNTIME_URL` | the endpoint behind the top bar's [runtime update button](versioning.md#runtime-updates)), such as a hosting platform's; without it there is no button |
371
371
  | `PROTOBASE_SENTRY_DSN` | the DSN of a Sentry-compatible error tracker the app's server and admin app send their errors to, after `options.errorReporting` ([Error reporting](api.md#error-reporting))); without it nothing is sent |
@@ -475,6 +475,21 @@ Turns a Supabase project's database into the project in the current directory, i
475
475
 
476
476
  Remove `supabase-import/` to import again. Signing in Supabase's users with Protobase's auth is not part of this command yet.
477
477
 
478
+ ## `mobile`
479
+
480
+ ```sh
481
+ protobase mobile run <ios|android> [--api <url>] [--target <id>] [--live] [--port 5173] [--extend <dir>]
482
+ protobase mobile open <ios|android> [--api <url>] [--extend <dir>]
483
+ ```
484
+
485
+ Builds the project in the current directory as an iOS or Android app with Capacitor, from the `mobile` section of its `protobase.config.ts`; without one it stops and says what to add. See [A mobile app](../guides/mobile-app.md)).
486
+
487
+ - It installs `@protobase/mobile`, of the CLI's version, which pins Capacitor and its plugins, with the section's `plugins` into `.protobase/mobile/` with npm, when that changed. It builds the app's files as [`build`](#build) does and keeps only `public/`, its `index.html` naming the API origin; writes `capacitor.config.json`, compiling in only the section's plugins; and generates the platform's native project again, replacing the last one.
488
+ - `--api` is the server the app calls, the project's auth `baseURL` by default: an http or https origin, plain http only to `localhost`, `127.0.0.1` and, on iOS, `[::1]`, or on Android `10.0.2.2`. An Android app calling `localhost` gets the port forwarded.
489
+ - `run` runs the app on `--target`, or asks for one. With `--live` it opens `protobase dev` on `localhost:--port` instead of its own files. `open` opens the native project in Xcode or Android Studio.
490
+ - npm and Capacitor get the CLI's environment without any variable named in the current directory's `.env*` files, and with `CI=true`, which keeps Capacitor's telemetry off.
491
+ - It prints the workspace, the API origin and the native fingerprint, which the app also sends in its user agent as `ProtobaseNative/<fingerprint>`: a hash of the `@protobase/mobile` version and the extra plugins' installed versions.
492
+
478
493
  ## `token`
479
494
 
480
495
  ```sh
@@ -385,7 +385,7 @@ export const repairsView = daily
385
385
 
386
386
  With displays, the list page has a switch at the right of its title: the table first, then each display by its `label`, with its `icon` (`table`, `cards`, `kanban`, `board`, `list`, `calendar` or `timeline`). Below the `md` breakpoint (768px) the switch is a menu of the same choices. The choice is in the address, `/repairs?display=cards`, so a reload, a bookmark or a shared link opens the same display; `default` names the display `/repairs` opens in, the table when it is left out. On a phone, below Tailwind's `sm` breakpoint (640px), a list with a cards display opens in it instead: the `default` when that is a cards display, else the first. A list without one opens in a built-in **List** there: a row per record with its `.title`, the first enum column as a badge on its right, and the next two columns but booleans on a muted line below, at `?display=rows`. The display menu offers the table beside it. A `?display=` in the address wins on any screen. A display without column headers has a sort menu over the sortable fields it shows, beside the filters, or below `md` in the filters sheet, whose button sits left of the search box. Selecting rows, deleting them in bulk and the row menu stay on the table, which every list keeps.
387
387
 
388
- The table, the cards, a board, a calendar and a timeline scroll with the page, which is as tall as all their rows, with the browser's own scrolling: only the rows and cards in view are drawn and loaded, so a list of any length scrolls at once, and Back returns to the same ones. The table's header stays below the top bar while the page scrolls. Every card is as tall as the tallest one drawn at that width. A custom display scrolls with the page as well, as every other page of the app does; the map fills the screen between the top bar and a phone's bottom bar instead, and does not scroll. Where scrollbars take room, as on Windows, the page keeps room for one even while it fits, so the cards keep their width as the scrollbar comes and goes.
388
+ The table, the cards, a board, a calendar and a timeline scroll with the page, which is as tall as all their rows, with the browser's own scrolling: only the rows and cards in view are drawn and loaded, so a list of any length scrolls at once. Coming back to the table or the cards, by Back or by a link to the same list, shows the same rows at the same height, after a reload too; another sort or filter starts at the top. The table's header stays below the top bar while the page scrolls. Every card is as tall as the tallest one drawn at that width. A custom display scrolls with the page as well, as every other page of the app does; the map fills the screen between the top bar and a phone's bottom bar instead, and does not scroll. Where scrollbars take room, as on Windows, the page keeps room for one even while it fits, so the cards keep their width as the scrollbar comes and goes.
389
389
 
390
390
  Display names are checked when the config loads: unique, not `table`, and `default` names one. Their fields are checked when the server starts, and may not be [sensitive](data-config.md#sensitive-fields)). In `/api/meta`, a user's displays lose the fields they cannot read, and a custom display whose `props` name one is left out; the list then opens in the table when its default display went.
391
391