usebecky 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.
Files changed (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,18 @@
1
+ import { UseBeckyError } from '../lib/errors.ts';
2
+ /** Your own WebAuthn implementation (React Native, Electron, tests): options JSON in, credential JSON out. */
3
+ export type PasskeyCreate = (options: Record<string, any>) => Promise<Record<string, any>>;
4
+ export type PasskeyGet = (options: Record<string, any>) => Promise<Record<string, any>>;
5
+ export declare function passkeysSupported(): boolean;
6
+ export declare function unsupported(): UseBeckyError;
7
+ /** What happened when the person closed the passkey sheet or the browser refused. */
8
+ export declare function webauthnError(err: unknown): UseBeckyError;
9
+ /** navigator.credentials.create with the server's options; returns the RegistrationResponseJSON. */
10
+ export declare function createCredential(options: Record<string, any>, custom?: PasskeyCreate): Promise<Record<string, any>>;
11
+ /** navigator.credentials.get with the server's options; returns the AuthenticationResponseJSON. */
12
+ export declare function getCredential(options: Record<string, any>, opts?: {
13
+ custom?: PasskeyGet;
14
+ autofill?: boolean;
15
+ signal?: AbortSignal;
16
+ }): Promise<Record<string, any>>;
17
+ /** The server doesn't know this passkey (deleted): ask the browser / password manager to forget it (where supported). */
18
+ export declare function forgetUnknownPasskey(rpId: string | undefined, credentialId: string | undefined): void;
@@ -0,0 +1,138 @@
1
+ // Passkeys in the browser: turn the server's WebAuthn options (JSON, base64url) into what navigator.credentials wants,
2
+ // and the browser's answer back into JSON. Uses PublicKeyCredential.parse*FromJSON / toJSON() where the browser has
3
+ // them, and converts by hand where it doesn't. React Native / Expo: pass your own `create` / `get` (e.g. from
4
+ // react-native-passkey) that takes the options JSON and returns the credential JSON.
5
+ import { UseBeckyError } from "../lib/errors.js";
6
+ const g = globalThis;
7
+ function toB64url(buf) {
8
+ const bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
9
+ let s = '';
10
+ for (const b of bytes)
11
+ s += String.fromCharCode(b);
12
+ return g.btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
13
+ }
14
+ function fromB64url(s) {
15
+ const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4);
16
+ const bin = g.atob(b64);
17
+ const out = new Uint8Array(bin.length);
18
+ for (let i = 0; i < bin.length; i++)
19
+ out[i] = bin.charCodeAt(i);
20
+ return out.buffer;
21
+ }
22
+ export function passkeysSupported() {
23
+ return typeof g.PublicKeyCredential === 'function' && typeof g.navigator?.credentials?.create === 'function';
24
+ }
25
+ export function unsupported() {
26
+ return new UseBeckyError({
27
+ code: 'passkeys_unsupported',
28
+ message: "This browser or app can't use passkeys.",
29
+ hint: 'Use a current browser (Chrome, Safari, Edge, Firefox). In React Native, pass your own create/get functions (for example from react-native-passkey), or use the Swift / Kotlin SDKs.',
30
+ status: 0,
31
+ });
32
+ }
33
+ /** What happened when the person closed the passkey sheet or the browser refused. */
34
+ export function webauthnError(err) {
35
+ const name = err?.name;
36
+ const message = err?.message ?? String(err);
37
+ if (name === 'NotAllowedError' || name === 'AbortError') {
38
+ return new UseBeckyError({ code: 'passkey_cancelled', message: 'The passkey request was cancelled or timed out.', hint: 'Try again and confirm with your fingerprint, face or device PIN.', status: 0 });
39
+ }
40
+ if (name === 'InvalidStateError') {
41
+ return new UseBeckyError({ code: 'passkey_exists', message: 'This device already has a passkey for this account.', hint: 'You can use it to sign in.', status: 0 });
42
+ }
43
+ if (name === 'SecurityError') {
44
+ return new UseBeckyError({
45
+ code: 'passkey_domain_mismatch',
46
+ message: "Passkeys can't be used on this page's domain.",
47
+ hint: `The passkey domain set in Dashboard → Auth → Sign-in methods → Passkeys must be this site's domain (or a parent of it). ${message}`,
48
+ status: 0,
49
+ });
50
+ }
51
+ return new UseBeckyError({ code: 'passkey_failed', message: `The passkey request failed: ${message}`, status: 0 });
52
+ }
53
+ function creationOptions(json) {
54
+ const PKC = g.PublicKeyCredential;
55
+ if (typeof PKC?.parseCreationOptionsFromJSON === 'function')
56
+ return PKC.parseCreationOptionsFromJSON(json);
57
+ return {
58
+ ...json,
59
+ challenge: fromB64url(json.challenge),
60
+ user: { ...json.user, id: fromB64url(json.user.id) },
61
+ excludeCredentials: (json.excludeCredentials ?? []).map((c) => ({ ...c, id: fromB64url(c.id) })),
62
+ };
63
+ }
64
+ function requestOptions(json) {
65
+ const PKC = g.PublicKeyCredential;
66
+ if (typeof PKC?.parseRequestOptionsFromJSON === 'function')
67
+ return PKC.parseRequestOptionsFromJSON(json);
68
+ return { ...json, challenge: fromB64url(json.challenge), allowCredentials: (json.allowCredentials ?? []).map((c) => ({ ...c, id: fromB64url(c.id) })) };
69
+ }
70
+ function credentialJson(cred) {
71
+ if (typeof cred?.toJSON === 'function') {
72
+ try {
73
+ return cred.toJSON();
74
+ }
75
+ catch { }
76
+ }
77
+ const r = cred.response;
78
+ const response = { clientDataJSON: toB64url(r.clientDataJSON) };
79
+ if (r.attestationObject) {
80
+ response.attestationObject = toB64url(r.attestationObject);
81
+ if (typeof r.getTransports === 'function')
82
+ response.transports = r.getTransports();
83
+ }
84
+ else {
85
+ response.authenticatorData = toB64url(r.authenticatorData);
86
+ response.signature = toB64url(r.signature);
87
+ if (r.userHandle)
88
+ response.userHandle = toB64url(r.userHandle);
89
+ }
90
+ return {
91
+ id: cred.id,
92
+ rawId: toB64url(cred.rawId),
93
+ type: cred.type ?? 'public-key',
94
+ authenticatorAttachment: cred.authenticatorAttachment ?? undefined,
95
+ response,
96
+ clientExtensionResults: typeof cred.getClientExtensionResults === 'function' ? cred.getClientExtensionResults() : {},
97
+ };
98
+ }
99
+ /** navigator.credentials.create with the server's options; returns the RegistrationResponseJSON. */
100
+ export async function createCredential(options, custom) {
101
+ if (custom)
102
+ return custom(options);
103
+ if (!passkeysSupported())
104
+ throw unsupported();
105
+ try {
106
+ const cred = await g.navigator.credentials.create({ publicKey: creationOptions(options) });
107
+ if (!cred)
108
+ throw new Error('No credential was created.');
109
+ return credentialJson(cred);
110
+ }
111
+ catch (err) {
112
+ throw webauthnError(err);
113
+ }
114
+ }
115
+ /** navigator.credentials.get with the server's options; returns the AuthenticationResponseJSON. */
116
+ export async function getCredential(options, opts = {}) {
117
+ if (opts.custom)
118
+ return opts.custom(options);
119
+ if (!passkeysSupported())
120
+ throw unsupported();
121
+ try {
122
+ const cred = await g.navigator.credentials.get({ publicKey: requestOptions(options), ...(opts.autofill ? { mediation: 'conditional' } : {}), ...(opts.signal ? { signal: opts.signal } : {}) });
123
+ if (!cred)
124
+ throw new Error('No passkey was chosen.');
125
+ return credentialJson(cred);
126
+ }
127
+ catch (err) {
128
+ throw webauthnError(err);
129
+ }
130
+ }
131
+ /** The server doesn't know this passkey (deleted): ask the browser / password manager to forget it (where supported). */
132
+ export function forgetUnknownPasskey(rpId, credentialId) {
133
+ try {
134
+ if (rpId && credentialId && typeof g.PublicKeyCredential?.signalUnknownCredential === 'function')
135
+ void g.PublicKeyCredential.signalUnknownCredential({ rpId, credentialId }).catch(() => { });
136
+ }
137
+ catch { }
138
+ }
@@ -0,0 +1,54 @@
1
+ import { type AppProject } from './framework.ts';
2
+ export declare const SKILL_NAME = "usebecky";
3
+ /** Where the skill is installed, relative to the project (forward slashes, for display). */
4
+ export declare const SKILL_TARGET = ".claude/skills/usebecky";
5
+ export declare const AGENTS_FILE = "AGENTS.md";
6
+ export declare const BLOCK_START = "<!-- usebecky:start -->";
7
+ export declare const BLOCK_END = "<!-- usebecky:end -->";
8
+ /**
9
+ * The skill ships at `<package>/skill/usebecky`. This file is `<package>/src/cli/ai.ts` in the repo
10
+ * and `<package>/dist/cli/ai.js` when installed, so look two levels up (and the levels between).
11
+ */
12
+ export declare function findSkillSource(fromDir?: string): string | null;
13
+ /** Files under `dir`, as sorted relative paths with forward slashes. */
14
+ export declare function listFiles(dir: string): string[];
15
+ export type FileStatus = 'created' | 'updated' | 'unchanged' | 'kept';
16
+ export interface FileResult {
17
+ /** Relative to the project, forward slashes: `.claude/skills/usebecky/SKILL.md`. */
18
+ path: string;
19
+ status: FileStatus;
20
+ }
21
+ /**
22
+ * Copy every skill file into `<cwd>/.claude/skills/usebecky/`. Missing files are created and identical
23
+ * files left alone. A file that differs (edited by the user, or from another version) is only
24
+ * replaced with `force`; otherwise it is kept and reported.
25
+ */
26
+ export declare function installSkill(source: string, cwd: string, force?: boolean): FileResult[];
27
+ /** Which rules AGENTS.md gets: a JavaScript app, a Swift (iOS) app, a Kotlin (Android) app, or `any` (mixed or not recognised). */
28
+ export type AgentsPlatform = 'js' | 'ios' | 'android' | 'any';
29
+ export declare const AGENTS_PLATFORMS: AgentsPlatform[];
30
+ export declare function agentsPlatformFor(project: AppProject): AgentsPlatform;
31
+ /** The AGENTS.md section: where the skill is, plus the rules agents get wrong most often on this platform. */
32
+ export declare function agentsBlock(platform?: AgentsPlatform): string;
33
+ export type AgentsStatus = 'created' | 'appended' | 'updated' | 'unchanged' | 'broken';
34
+ /**
35
+ * Put `block` into AGENTS.md content: create it, append it, or replace the existing block in place
36
+ * (extra copies are removed, so it is never duplicated). A start marker without an end marker is
37
+ * `broken` and left alone, unless `force`, which replaces everything from the start marker on.
38
+ */
39
+ export declare function mergeAgentsBlock(existing: string | null, block: string, force?: boolean): {
40
+ content: string;
41
+ status: AgentsStatus;
42
+ };
43
+ /**
44
+ * Create or update `<cwd>/AGENTS.md`. Writes only when something changed. The rules fit the app found
45
+ * in `cwd` (JavaScript, Swift, Kotlin, or all of them) unless `platform` is given.
46
+ */
47
+ export declare function writeAgentsFile(cwd: string, force?: boolean, platform?: AgentsPlatform): {
48
+ path: string;
49
+ status: AgentsStatus;
50
+ platform: AgentsPlatform;
51
+ };
52
+ /** What to try first, printed after installing (web and Node apps). */
53
+ export declare const EXAMPLE_PROMPTS: string[];
54
+ export declare function examplePromptsFor(platform: AgentsPlatform): string[];
package/dist/cli/ai.js ADDED
@@ -0,0 +1,202 @@
1
+ // `npx usebecky ai` (alias `skill`): teach AI coding assistants how to use usebecky.
2
+ // Copies the bundled skill (packages/sdk/skill/usebecky) into .claude/skills/usebecky/ and keeps a
3
+ // delimited usebecky section in AGENTS.md for Cursor, Codex, Copilot, Windsurf and others. The
4
+ // AGENTS.md rules fit the app: JavaScript, Swift (iOS), Kotlin (Android), or all of them.
5
+ // Pure functions over directories so they are easy to test.
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { detectProject } from "./framework.js";
10
+ export const SKILL_NAME = 'usebecky';
11
+ /** Where the skill is installed, relative to the project (forward slashes, for display). */
12
+ export const SKILL_TARGET = `.claude/skills/${SKILL_NAME}`;
13
+ export const AGENTS_FILE = 'AGENTS.md';
14
+ export const BLOCK_START = '<!-- usebecky:start -->';
15
+ export const BLOCK_END = '<!-- usebecky:end -->';
16
+ /**
17
+ * The skill ships at `<package>/skill/usebecky`. This file is `<package>/src/cli/ai.ts` in the repo
18
+ * and `<package>/dist/cli/ai.js` when installed, so look two levels up (and the levels between).
19
+ */
20
+ export function findSkillSource(fromDir = path.dirname(fileURLToPath(import.meta.url))) {
21
+ let dir = path.resolve(fromDir);
22
+ for (let i = 0; i < 3; i++) {
23
+ const candidate = path.join(dir, 'skill', SKILL_NAME);
24
+ if (fs.existsSync(path.join(candidate, 'SKILL.md')))
25
+ return candidate;
26
+ const parent = path.dirname(dir);
27
+ if (parent === dir)
28
+ break;
29
+ dir = parent;
30
+ }
31
+ return null;
32
+ }
33
+ /** Files under `dir`, as sorted relative paths with forward slashes. */
34
+ export function listFiles(dir) {
35
+ const out = [];
36
+ const walk = (rel) => {
37
+ for (const entry of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
38
+ if (entry.name.startsWith('.'))
39
+ continue;
40
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
41
+ if (entry.isDirectory())
42
+ walk(child);
43
+ else if (entry.isFile())
44
+ out.push(child);
45
+ }
46
+ };
47
+ walk('');
48
+ return out.sort();
49
+ }
50
+ /**
51
+ * Copy every skill file into `<cwd>/.claude/skills/usebecky/`. Missing files are created and identical
52
+ * files left alone. A file that differs (edited by the user, or from another version) is only
53
+ * replaced with `force`; otherwise it is kept and reported.
54
+ */
55
+ export function installSkill(source, cwd, force = false) {
56
+ const target = path.join(cwd, ...SKILL_TARGET.split('/'));
57
+ return listFiles(source).map((rel) => {
58
+ const display = `${SKILL_TARGET}/${rel}`;
59
+ const content = fs.readFileSync(path.join(source, ...rel.split('/')));
60
+ const dest = path.join(target, ...rel.split('/'));
61
+ if (!fs.existsSync(dest)) {
62
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
63
+ fs.writeFileSync(dest, content);
64
+ return { path: display, status: 'created' };
65
+ }
66
+ if (fs.readFileSync(dest).equals(content))
67
+ return { path: display, status: 'unchanged' };
68
+ if (!force)
69
+ return { path: display, status: 'kept' };
70
+ fs.writeFileSync(dest, content);
71
+ return { path: display, status: 'updated' };
72
+ });
73
+ }
74
+ export const AGENTS_PLATFORMS = ['js', 'ios', 'android', 'any'];
75
+ export function agentsPlatformFor(project) {
76
+ if (project.kind === 'js')
77
+ return 'js';
78
+ if (project.kind === 'native' && project.native.platforms.length === 1)
79
+ return project.native.platforms[0];
80
+ return 'any';
81
+ }
82
+ const RULE_ACCESS = `Access rules first. Row Level Security is on for every table; without a policy, reads return no rows, inserts fail with \`permission_denied\` and updates/deletes silently change nothing. Write the table, its policies (usually \`user_id = auth.uid()\`) and the queries in the same change, and give the user the SQL to run.`;
83
+ function rulesFor(platform) {
84
+ const skill = `\`${SKILL_TARGET}/SKILL.md\``;
85
+ if (platform === 'ios') {
86
+ return {
87
+ intro: `This app uses usebecky (sign-in, Postgres database, access rules, file storage, realtime, Stripe payments, push notifications, forms, newsletter) through the native Swift package \`UseBecky\`. Before you write or change anything that touches sign-in, data, access rules, files, realtime or payments, read ${skill}, then \`${SKILL_TARGET}/references/ios.md\` (the Swift API). Use only the APIs documented there. Never add npm packages or JavaScript to this app.`,
88
+ rules: [
89
+ 'Never put the secret key (`ub_sk_...`) in the app: anyone can read every value inside an app. The app uses only the Project URL and the publishable key (`ub_pk_...`): `let baas = UseBecky(url: "...", publishableKey: "ub_pk_...")`. Work that needs the secret key (sending push notifications or emails, admin tasks) runs on a server or in the dashboard.',
90
+ RULE_ACCESS,
91
+ 'Every call is `try await` and throws `UseBeckyError` (`code`, `message`, `hint`). Always wrap calls in `do { ... } catch { ... }` and show `error.localizedDescription`; Swift calls do not return a `data`/`error` pair.',
92
+ 'usebecky is not Supabase or Firebase. Use `baas.auth.signInWithApple()`, `baas.auth.signIn(email:password:)`, `baas.auth.signIn(with: .google, redirectTo:)`, `baas.from("notes").select().execute()` and `baas.realtime.subscribe(table:)`; never supabase-swift or Firebase APIs.',
93
+ 'Social sign-in returns through a URL scheme equal to the bundle ID (`com.example.mynotes://auth`): register it under the target\'s URL Types and allow `com.example.mynotes://**` in Dashboard → Settings → General → Your app’s addresses. Offer Sign in with Apple first.',
94
+ ],
95
+ };
96
+ }
97
+ if (platform === 'android') {
98
+ return {
99
+ intro: `This app uses usebecky (sign-in, Postgres database, access rules, file storage, realtime, Stripe payments, push notifications, forms, newsletter) through the native Kotlin SDK \`com.usebecky:usebecky-kotlin\`. Before you write or change anything that touches sign-in, data, access rules, files, realtime or payments, read ${skill}, then \`${SKILL_TARGET}/references/android.md\` (the Kotlin API). Use only the APIs documented there. Never add npm packages or JavaScript to this app.`,
100
+ rules: [
101
+ 'Never put the secret key (`ub_sk_...`) in the app: anyone can read every value inside an app (the SDK refuses it with `secret_key_in_app`). The app uses only the Project URL and the publishable key (`ub_pk_...`). Work that needs the secret key (sending push notifications or emails, admin tasks) runs on a server or in the dashboard.',
102
+ RULE_ACCESS,
103
+ 'Every call is a `suspend` function that throws `UseBeckyException` (`code`, `message`, `hint`). Always wrap calls in `try { ... } catch (e: UseBeckyException) { ... }`: an uncaught throw in a coroutine crashes the app. Kotlin calls do not return a `data`/`error` pair.',
104
+ 'usebecky is not Supabase or Firebase. Use `baas.auth.signIn(email, password)`, `baas.auth.signInWithIdToken("google", idToken, rawNonce)` (Credential Manager), `baas.from("notes").select().list<Note>()` and `baas.realtime.subscribe("notes")`; never supabase-kt, Firebase Auth or Firestore APIs.',
105
+ 'Social sign-in returns through a URL scheme equal to the application ID (`com.example.mynotes://auth`): add it to the intent filter and allow `com.example.mynotes://**` in Dashboard → Settings → General → Your app’s addresses. Offer Google sign-in with Credential Manager first.',
106
+ ],
107
+ };
108
+ }
109
+ const secret = 'Never expose the secret key. `ub_sk_...` / `USEBECKY_SECRET_KEY` stays in server code (`usebecky/server`); never put it in browser or mobile code or in a `NEXT_PUBLIC_`, `VITE_`, `PUBLIC_` or `EXPO_PUBLIC_` variable.';
110
+ const notSupabase = "usebecky is not Supabase. Use `auth.signIn`, `auth.signInWith('google')`, `auth.sendMagicLink` and `realtime.subscribe(table, options, callback)`; never supabase-js names such as `signInWithPassword`, `signInWithOAuth` or `channel().on('postgres_changes')`.";
111
+ const server = 'On the server, act as the user with `baas.as(req)` (RLS applies). Use `baas.admin` (bypasses RLS) only in trusted code, never to work around a missing policy.';
112
+ if (platform === 'js') {
113
+ return {
114
+ intro: `This app uses usebecky (auth, Postgres database, access rules, storage, realtime, Stripe payments, webhooks, push, forms, newsletter, emails) through the \`usebecky\` npm package. Before you write or change anything that touches sign-in, data, access rules, files, realtime, payments or webhooks, read ${skill} and the reference files it points to. Use only the APIs documented there.`,
115
+ rules: [
116
+ `${secret} Browser and app code uses \`createClient\` from \`usebecky\` with the publishable key.`,
117
+ RULE_ACCESS,
118
+ 'JavaScript calls return `{ data, error }` and never throw. Check `error` before using `data`. (The Swift and Kotlin SDKs throw instead; see the skill.)',
119
+ notSupabase,
120
+ server,
121
+ ],
122
+ };
123
+ }
124
+ return {
125
+ intro: `This project uses usebecky (auth, Postgres database, access rules, storage, realtime, Stripe payments, webhooks, push, forms, newsletter, emails). Web, Node and Expo code use the \`usebecky\` npm package; iOS apps use the Swift package \`UseBecky\` (read \`${SKILL_TARGET}/references/ios.md\`); Android apps use the Kotlin SDK \`com.usebecky:usebecky-kotlin\` (read \`${SKILL_TARGET}/references/android.md\`). Before you write or change anything that touches sign-in, data, access rules, files, realtime, payments or webhooks, read ${skill} and the reference files it points to. Use only the APIs documented there. Never add npm packages to a Swift or Kotlin app.`,
126
+ rules: [
127
+ `${secret} Browsers and apps (Swift, Kotlin, Expo) use only the publishable key \`ub_pk_...\`.`,
128
+ RULE_ACCESS,
129
+ 'Handle errors the way each SDK reports them. JavaScript: every call returns `{ data, error }` and never throws; check `error` before using `data`. Swift: calls throw `UseBeckyError`; always `do { try await ... } catch { ... }`. Kotlin: calls throw `UseBeckyException`; always `try { ... } catch (e: UseBeckyException) { ... }`.',
130
+ `${notSupabase} In Swift and Kotlin use the names in the iOS and Android references.`,
131
+ server,
132
+ ],
133
+ };
134
+ }
135
+ /** The AGENTS.md section: where the skill is, plus the rules agents get wrong most often on this platform. */
136
+ export function agentsBlock(platform = 'any') {
137
+ const { intro, rules } = rulesFor(platform);
138
+ return `${BLOCK_START}
139
+ ## Backend: usebecky
140
+
141
+ ${intro}
142
+
143
+ Rules:
144
+
145
+ ${rules.map((r, i) => `${i + 1}. ${r}`).join('\n')}
146
+ ${BLOCK_END}`;
147
+ }
148
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
149
+ const BLOCK_RE = new RegExp(`${escapeRe(BLOCK_START)}[\\s\\S]*?${escapeRe(BLOCK_END)}`, 'g');
150
+ const DUPLICATE = '\u0000usebecky-duplicate\u0000';
151
+ /**
152
+ * Put `block` into AGENTS.md content: create it, append it, or replace the existing block in place
153
+ * (extra copies are removed, so it is never duplicated). A start marker without an end marker is
154
+ * `broken` and left alone, unless `force`, which replaces everything from the start marker on.
155
+ */
156
+ export function mergeAgentsBlock(existing, block, force = false) {
157
+ if (existing === null)
158
+ return { content: `${block}\n`, status: 'created' };
159
+ const eol = existing.includes('\r\n') ? '\r\n' : '\n';
160
+ const ours = block.replace(/\r?\n/g, eol);
161
+ const matches = existing.match(BLOCK_RE);
162
+ if (!matches) {
163
+ const start = existing.indexOf(BLOCK_START);
164
+ if (start >= 0) {
165
+ if (!force)
166
+ return { content: existing, status: 'broken' };
167
+ return { content: `${existing.slice(0, start)}${ours}${eol}`, status: 'updated' };
168
+ }
169
+ const trimmed = existing.replace(/\s+$/, '');
170
+ return { content: trimmed ? `${trimmed}${eol}${eol}${ours}${eol}` : `${ours}${eol}`, status: 'appended' };
171
+ }
172
+ let seen = 0;
173
+ const content = existing
174
+ .replace(BLOCK_RE, () => (seen++ === 0 ? ours : DUPLICATE))
175
+ .replace(new RegExp(`(?:\\r?\\n)*${DUPLICATE}`, 'g'), '');
176
+ return { content, status: content === existing ? 'unchanged' : 'updated' };
177
+ }
178
+ /**
179
+ * Create or update `<cwd>/AGENTS.md`. Writes only when something changed. The rules fit the app found
180
+ * in `cwd` (JavaScript, Swift, Kotlin, or all of them) unless `platform` is given.
181
+ */
182
+ export function writeAgentsFile(cwd, force = false, platform = agentsPlatformFor(detectProject(cwd))) {
183
+ const file = path.join(cwd, AGENTS_FILE);
184
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
185
+ const result = mergeAgentsBlock(existing, agentsBlock(platform), force);
186
+ if (result.status !== 'unchanged' && result.status !== 'broken')
187
+ fs.writeFileSync(file, result.content);
188
+ return { path: AGENTS_FILE, status: result.status, platform };
189
+ }
190
+ /** What to try first, printed after installing (web and Node apps). */
191
+ export const EXAMPLE_PROMPTS = [
192
+ 'Add sign-in with Google and a private notes table',
193
+ 'Let users upload a profile picture',
194
+ 'Add a Pro plan with Stripe and hide premium pages from free users',
195
+ ];
196
+ export function examplePromptsFor(platform) {
197
+ if (platform === 'ios')
198
+ return ['Add Sign in with Apple and a private notes list', 'Let users pick a profile photo and upload it', 'Add a newsletter sign-up to the settings screen'];
199
+ if (platform === 'android')
200
+ return ['Add Google sign-in with Credential Manager and a private notes list', 'Let users pick a profile photo and upload it', 'Add a newsletter sign-up to the settings screen'];
201
+ return EXAMPLE_PROMPTS;
202
+ }
@@ -0,0 +1,53 @@
1
+ import { type Ui } from './ui.ts';
2
+ /** Where the script is served (GET, public). */
3
+ export declare const SCRIPT_PATH = "/analytics/v1/script.js";
4
+ /** The last line `analytics` prints. */
5
+ export declare const TURN_ON = "Now turn analytics on in your dashboard: Analytics \u2192 Turn on";
6
+ /** The tag, exactly as the server builds it (GET /platform/v1/projects/:ref/analytics/status → snippet). */
7
+ export declare function snippetFor(apiUrl: string, key: string): string;
8
+ export type SiteKind = 'next' | 'astro' | 'sveltekit' | 'nuxt' | 'remix' | 'html' | 'app' | 'native' | 'unknown';
9
+ export interface Site {
10
+ kind: SiteKind;
11
+ /** For people: "Next.js (App Router)", "a plain HTML site", ... */
12
+ label: string;
13
+ /** Files to edit or create, relative to the folder. */
14
+ files: string[];
15
+ }
16
+ export interface FileChange {
17
+ file: string;
18
+ status: 'created' | 'added' | 'updated' | 'unchanged' | 'manual';
19
+ /** New content (created / added / updated). */
20
+ content?: string;
21
+ /** Lines to show people: what was added or changed. */
22
+ lines: string[];
23
+ /** Why nothing was changed and what to do instead (status 'manual'). */
24
+ note?: string;
25
+ }
26
+ /** Which kind of website lives in `dir`, and which files get the tag. */
27
+ export declare function detectSite(dir: string): Site;
28
+ /** What would change in each of the site's files. Nothing is written. */
29
+ export declare function planAnalytics(dir: string, site: Site, apiUrl: string, key: string): FileChange[];
30
+ export declare function writeChanges(dir: string, changes: FileChange[]): void;
31
+ export interface AnalyticsContext {
32
+ cwd: string;
33
+ ui: Ui;
34
+ /** Interactive questions allowed (false with --yes). */
35
+ interactive: boolean;
36
+ flags: {
37
+ key?: string;
38
+ apiUrl?: string;
39
+ dryRun?: boolean;
40
+ };
41
+ /** The API address to use when neither --api-url nor the env file names one (the hosted API, or USEBECKY_API_URL). */
42
+ defaultApiUrl: string;
43
+ /** From the env file `usebecky init` wrote (publishable key and Project URL only). */
44
+ linked: {
45
+ ref: string | null;
46
+ url: string | null;
47
+ key: string | null;
48
+ file: string | null;
49
+ };
50
+ /** The project's dashboard page, when it can be found. */
51
+ dashboard: (ref: string) => Promise<string | null>;
52
+ }
53
+ export declare function analyticsCommand(ctx: AnalyticsContext): Promise<number>;