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.
- package/README.md +701 -2
- package/dist/analytics/client.d.ts +219 -0
- package/dist/analytics/client.js +923 -0
- package/dist/analytics/cmp.d.ts +20 -0
- package/dist/analytics/cmp.js +166 -0
- package/dist/analytics/context.d.ts +29 -0
- package/dist/analytics/context.js +97 -0
- package/dist/auth/client.d.ts +401 -0
- package/dist/auth/client.js +1081 -0
- package/dist/auth/webauthn.d.ts +18 -0
- package/dist/auth/webauthn.js +138 -0
- package/dist/cli/ai.d.ts +54 -0
- package/dist/cli/ai.js +202 -0
- package/dist/cli/analytics.d.ts +53 -0
- package/dist/cli/analytics.js +357 -0
- package/dist/cli/config.d.ts +75 -0
- package/dist/cli/config.js +718 -0
- package/dist/cli/db.d.ts +48 -0
- package/dist/cli/db.js +215 -0
- package/dist/cli/deploy-api.d.ts +168 -0
- package/dist/cli/deploy-api.js +177 -0
- package/dist/cli/deploy-ci.d.ts +15 -0
- package/dist/cli/deploy-ci.js +54 -0
- package/dist/cli/deploy-detect.d.ts +64 -0
- package/dist/cli/deploy-detect.js +249 -0
- package/dist/cli/deploy-files.d.ts +112 -0
- package/dist/cli/deploy-files.js +778 -0
- package/dist/cli/deploy.d.ts +10 -0
- package/dist/cli/deploy.js +430 -0
- package/dist/cli/emails.d.ts +29 -0
- package/dist/cli/emails.js +122 -0
- package/dist/cli/framework.d.ts +135 -0
- package/dist/cli/framework.js +459 -0
- package/dist/cli/functions.d.ts +59 -0
- package/dist/cli/functions.js +426 -0
- package/dist/cli/hosting.d.ts +4 -0
- package/dist/cli/hosting.js +532 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/payments.d.ts +35 -0
- package/dist/cli/payments.js +176 -0
- package/dist/cli/push.d.ts +36 -0
- package/dist/cli/push.js +172 -0
- package/dist/cli/run.d.ts +65 -0
- package/dist/cli/run.js +850 -0
- package/dist/cli/social.d.ts +52 -0
- package/dist/cli/social.js +532 -0
- package/dist/cli/tokens.d.ts +28 -0
- package/dist/cli/tokens.js +114 -0
- package/dist/cli/ui.d.ts +38 -0
- package/dist/cli/ui.js +140 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +156 -0
- package/dist/db/query.d.ts +162 -0
- package/dist/db/query.js +336 -0
- package/dist/db/types.d.ts +93 -0
- package/dist/db/types.js +4 -0
- package/dist/forms/client.d.ts +65 -0
- package/dist/forms/client.js +106 -0
- package/dist/functions/client.d.ts +37 -0
- package/dist/functions/client.js +76 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +16 -0
- package/dist/lib/dashboard-paths.d.ts +4 -0
- package/dist/lib/dashboard-paths.js +8 -0
- package/dist/lib/env.d.ts +9 -0
- package/dist/lib/env.js +55 -0
- package/dist/lib/errors.d.ts +22 -0
- package/dist/lib/errors.js +90 -0
- package/dist/lib/hosted.d.ts +2 -0
- package/dist/lib/hosted.js +7 -0
- package/dist/lib/http.d.ts +59 -0
- package/dist/lib/http.js +172 -0
- package/dist/lib/jwt.d.ts +1 -0
- package/dist/lib/jwt.js +31 -0
- package/dist/lib/locale.d.ts +12 -0
- package/dist/lib/locale.js +51 -0
- package/dist/lib/pkce.d.ts +20 -0
- package/dist/lib/pkce.js +124 -0
- package/dist/lib/storage-adapter.d.ts +15 -0
- package/dist/lib/storage-adapter.js +91 -0
- package/dist/lib/types.d.ts +339 -0
- package/dist/lib/types.js +1 -0
- package/dist/newsletter/client.d.ts +140 -0
- package/dist/newsletter/client.js +85 -0
- package/dist/payments/client.d.ts +352 -0
- package/dist/payments/client.js +323 -0
- package/dist/push/client.d.ts +110 -0
- package/dist/push/client.js +179 -0
- package/dist/realtime/client.d.ts +131 -0
- package/dist/realtime/client.js +513 -0
- package/dist/server/analytics.d.ts +176 -0
- package/dist/server/analytics.js +49 -0
- package/dist/server/cache.d.ts +74 -0
- package/dist/server/cache.js +154 -0
- package/dist/server/emails.d.ts +142 -0
- package/dist/server/emails.js +123 -0
- package/dist/server/events.d.ts +357 -0
- package/dist/server/events.js +219 -0
- package/dist/server/functions.d.ts +40 -0
- package/dist/server/functions.js +1 -0
- package/dist/server/http-utils.d.ts +10 -0
- package/dist/server/http-utils.js +115 -0
- package/dist/server/index.d.ts +195 -0
- package/dist/server/index.js +314 -0
- package/dist/server/payments.d.ts +218 -0
- package/dist/server/payments.js +150 -0
- package/dist/server/push.d.ts +85 -0
- package/dist/server/push.js +37 -0
- package/dist/server/usage.d.ts +43 -0
- package/dist/server/usage.js +8 -0
- package/dist/storage/client.d.ts +143 -0
- package/dist/storage/client.js +224 -0
- package/package.json +52 -4
- package/skill/usebecky/SKILL.md +339 -0
- package/skill/usebecky/references/access-rules.md +307 -0
- package/skill/usebecky/references/addons.md +68 -0
- package/skill/usebecky/references/analytics.md +166 -0
- package/skill/usebecky/references/android.md +434 -0
- package/skill/usebecky/references/auth.md +379 -0
- package/skill/usebecky/references/cache.md +51 -0
- package/skill/usebecky/references/components.md +127 -0
- package/skill/usebecky/references/emails.md +105 -0
- package/skill/usebecky/references/expo.md +147 -0
- package/skill/usebecky/references/functions.md +99 -0
- package/skill/usebecky/references/hosting.md +119 -0
- package/skill/usebecky/references/http-api.md +233 -0
- package/skill/usebecky/references/ios.md +355 -0
- package/skill/usebecky/references/payments.md +493 -0
- package/skill/usebecky/references/realtime.md +143 -0
- package/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/skill/usebecky/references/sdk.md +838 -0
- package/skill/usebecky/references/storage.md +210 -0
- package/skill/usebecky/references/templates.md +191 -0
- package/skill/usebecky/references/wordpress.md +87 -0
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
// `npx usebecky analytics`: puts the visitor analytics <script> tag in the right file of a website.
|
|
2
|
+
// Finds the publishable key and API URL (flags, the env file `usebecky init` wrote, or asks), detects the
|
|
3
|
+
// framework, inserts the tag once (running it again changes nothing, or updates the key / URL), prints
|
|
4
|
+
// exactly what changed, and supports --dry-run. Never reads or writes the secret key.
|
|
5
|
+
// The detection and file edits are pure functions over a folder, so they are easy to test.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { DASHBOARD_API_KEYS } from "../lib/dashboard-paths.js";
|
|
9
|
+
import { DOCS_URL, detectProject } from "./framework.js";
|
|
10
|
+
import { c } from "./ui.js";
|
|
11
|
+
/** Where the script is served (GET, public). */
|
|
12
|
+
export const SCRIPT_PATH = '/analytics/v1/script.js';
|
|
13
|
+
/** The last line `analytics` prints. */
|
|
14
|
+
export const TURN_ON = 'Now turn analytics on in your dashboard: Analytics → Turn on';
|
|
15
|
+
const GUIDE = `${DOCS_URL}/guides/analytics`;
|
|
16
|
+
const EXISTING = /\/analytics\/v1\/script\.js/;
|
|
17
|
+
/** The tag, exactly as the server builds it (GET /platform/v1/projects/:ref/analytics/status → snippet). */
|
|
18
|
+
export function snippetFor(apiUrl, key) {
|
|
19
|
+
return `<script defer src="${apiUrl.replace(/\/+$/, '')}${SCRIPT_PATH}" data-key="${key}"></script>`;
|
|
20
|
+
}
|
|
21
|
+
const exists = (dir, f) => fs.existsSync(path.join(dir, f));
|
|
22
|
+
const firstExisting = (dir, files) => files.find((f) => exists(dir, f));
|
|
23
|
+
const read = (dir, f) => fs.readFileSync(path.join(dir, f), 'utf8');
|
|
24
|
+
/** Files under `dir`/`sub` (recursive, at most `depth` levels) whose name matches `re`. */
|
|
25
|
+
function filesUnder(dir, sub, re, depth = 3) {
|
|
26
|
+
const out = [];
|
|
27
|
+
const walk = (rel, level) => {
|
|
28
|
+
let entries;
|
|
29
|
+
try {
|
|
30
|
+
entries = fs.readdirSync(path.join(dir, rel), { withFileTypes: true });
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
36
|
+
const child = rel ? `${rel}/${e.name}` : e.name;
|
|
37
|
+
if (e.isDirectory()) {
|
|
38
|
+
if (level < depth && e.name !== 'node_modules' && !e.name.startsWith('.'))
|
|
39
|
+
walk(child, level + 1);
|
|
40
|
+
}
|
|
41
|
+
else if (re.test(e.name))
|
|
42
|
+
out.push(child);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
walk(sub, 1);
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
const has = (d, name) => Object.prototype.hasOwnProperty.call(d.dependencies, name);
|
|
49
|
+
const hasPrefix = (d, prefix) => Object.keys(d.dependencies).some((n) => n.startsWith(prefix));
|
|
50
|
+
const EXT = ['tsx', 'jsx', 'ts', 'js'];
|
|
51
|
+
/** Which kind of website lives in `dir`, and which files get the tag. */
|
|
52
|
+
export function detectSite(dir) {
|
|
53
|
+
const app = detectProject(dir);
|
|
54
|
+
if (app.kind === 'native')
|
|
55
|
+
return { kind: 'native', label: 'an iOS or Android app', files: [] };
|
|
56
|
+
const d = app.detected;
|
|
57
|
+
if (d.framework === 'expo')
|
|
58
|
+
return { kind: 'app', label: d.label, files: [] };
|
|
59
|
+
if (d.framework === 'next') {
|
|
60
|
+
const layout = firstExisting(dir, ['app', 'src/app'].flatMap((base) => EXT.map((e) => `${base}/layout.${e}`)));
|
|
61
|
+
const pagesDir = firstExisting(dir, ['pages', 'src/pages']);
|
|
62
|
+
const files = [];
|
|
63
|
+
if (layout)
|
|
64
|
+
files.push(layout);
|
|
65
|
+
if (pagesDir)
|
|
66
|
+
files.push(firstExisting(dir, EXT.map((e) => `${pagesDir}/_document.${e}`)) ?? `${pagesDir}/_document.${d.typescript ? 'tsx' : 'js'}`);
|
|
67
|
+
const label = layout && pagesDir ? 'Next.js (App Router and Pages Router)' : pagesDir ? 'Next.js (Pages Router)' : 'Next.js (App Router)';
|
|
68
|
+
return { kind: files.length ? 'next' : 'unknown', label, files };
|
|
69
|
+
}
|
|
70
|
+
if (has(d, 'astro')) {
|
|
71
|
+
const withHead = (files) => files.filter((f) => /<\/head>/i.test(read(dir, f)));
|
|
72
|
+
const layouts = withHead(filesUnder(dir, 'src/layouts', /\.astro$/));
|
|
73
|
+
return { kind: 'astro', label: 'Astro', files: layouts.length ? layouts : withHead(filesUnder(dir, 'src/pages', /\.astro$/)) };
|
|
74
|
+
}
|
|
75
|
+
if (d.framework === 'sveltekit')
|
|
76
|
+
return { kind: 'sveltekit', label: 'SvelteKit', files: exists(dir, 'src/app.html') ? ['src/app.html'] : [] };
|
|
77
|
+
if (d.framework === 'nuxt') {
|
|
78
|
+
const config = firstExisting(dir, ['nuxt.config.ts', 'nuxt.config.js', 'nuxt.config.mjs']);
|
|
79
|
+
return { kind: 'nuxt', label: 'Nuxt', files: config ? [config] : [] };
|
|
80
|
+
}
|
|
81
|
+
const reactRouter = has(d, '@react-router/dev');
|
|
82
|
+
if (d.framework === 'remix' || reactRouter) {
|
|
83
|
+
const root = firstExisting(dir, EXT.map((e) => `app/root.${e}`));
|
|
84
|
+
if (root)
|
|
85
|
+
return { kind: 'remix', label: reactRouter ? 'React Router' : 'Remix', files: [root] };
|
|
86
|
+
}
|
|
87
|
+
// A plain index.html: Vite at the top, Create React App / Vue CLI in public/, Angular in src/.
|
|
88
|
+
if (!d.hasPackageJson) {
|
|
89
|
+
const pages = filesUnder(dir, '', /\.html?$/i, 1);
|
|
90
|
+
if (pages.length)
|
|
91
|
+
return { kind: 'html', label: 'a plain HTML site', files: pages };
|
|
92
|
+
}
|
|
93
|
+
const index = firstExisting(dir, ['index.html', 'public/index.html', 'src/index.html']);
|
|
94
|
+
if (index) {
|
|
95
|
+
const label = has(d, 'react-scripts') ? 'Create React App' : has(d, '@angular/core') ? 'Angular' : d.framework === 'vite' ? 'Vite' : d.hasPackageJson ? d.label : 'a plain HTML site';
|
|
96
|
+
return { kind: 'html', label, files: [index] };
|
|
97
|
+
}
|
|
98
|
+
return { kind: 'unknown', label: d.hasPackageJson ? d.label : 'this folder', files: [] };
|
|
99
|
+
}
|
|
100
|
+
// ---- edits --------------------------------------------------------------------------------------
|
|
101
|
+
const indentOf = (line) => /^\s*/.exec(line)[0];
|
|
102
|
+
/** Inserts `snippet` on its own line before the line holding `close` (like `</head>`), indented one level
|
|
103
|
+
* deeper than `close` (or like the line before it). Null when `close` isn't there. */
|
|
104
|
+
function insertBefore(content, close, snippet) {
|
|
105
|
+
const m = close.exec(content);
|
|
106
|
+
if (!m)
|
|
107
|
+
return null;
|
|
108
|
+
const lineStart = content.lastIndexOf('\n', m.index - 1) + 1;
|
|
109
|
+
const before = content.slice(lineStart, m.index);
|
|
110
|
+
if (before.trim())
|
|
111
|
+
return content.slice(0, m.index) + snippet + content.slice(m.index); // minified: same line
|
|
112
|
+
const closeIndent = before;
|
|
113
|
+
const prevLine = content.slice(0, lineStart).replace(/\n+$/, '').split('\n').pop() ?? '';
|
|
114
|
+
const unit = /^\t/m.test(content) ? '\t' : ' ';
|
|
115
|
+
const indent = indentOf(prevLine).length > closeIndent.length ? indentOf(prevLine) : closeIndent + unit;
|
|
116
|
+
return content.slice(0, lineStart) + indent + snippet + '\n' + content.slice(lineStart);
|
|
117
|
+
}
|
|
118
|
+
/** Points an existing tag at `src` / `key`, keeping any other attributes people added. */
|
|
119
|
+
function updateTag(tag, src, key) {
|
|
120
|
+
let t = tag.replace(/\bsrc=(["'])[^"']*\1/, `src="${src}"`);
|
|
121
|
+
t = /\bdata-key=(["'])[^"']*\1/.test(t) ? t.replace(/\bdata-key=(["'])[^"']*\1/, `data-key="${key}"`) : t.replace(/\bsrc="[^"]*"/, (s) => `${s} data-key="${key}"`);
|
|
122
|
+
return t;
|
|
123
|
+
}
|
|
124
|
+
/** The existing tag (HTML, JSX or <Script>) in `content`, if any. */
|
|
125
|
+
const TAG = /<(script|Script)\b[^>]*\/analytics\/v1\/script\.js[^>]*?(?:\/>|>\s*<\/(?:script|Script)>)/;
|
|
126
|
+
function tagChange(file, content, src, key, insert, manual) {
|
|
127
|
+
const m = TAG.exec(content);
|
|
128
|
+
if (m) {
|
|
129
|
+
const next = updateTag(m[0], src, key);
|
|
130
|
+
if (next === m[0])
|
|
131
|
+
return { file, status: 'unchanged', lines: [] };
|
|
132
|
+
return { file, status: 'updated', content: content.replace(m[0], next), lines: [`- ${m[0].trim()}`, `+ ${next.trim()}`] };
|
|
133
|
+
}
|
|
134
|
+
if (EXISTING.test(content))
|
|
135
|
+
return { file, status: 'manual', lines: [], note: `${file} mentions ${SCRIPT_PATH} in a way this command can't update. Check its src and data-key by hand.` };
|
|
136
|
+
const r = insert();
|
|
137
|
+
return r ? { file, status: 'added', content: r.content, lines: r.lines } : { file, status: 'manual', lines: [], note: manual };
|
|
138
|
+
}
|
|
139
|
+
/** Head of an HTML page, an Astro layout, SvelteKit's app.html or Remix's root.tsx (JSX accepts the tag as is). */
|
|
140
|
+
function headChange(file, content, apiUrl, key, astro = false) {
|
|
141
|
+
const src = `${apiUrl.replace(/\/+$/, '')}${SCRIPT_PATH}`;
|
|
142
|
+
const tag = astro ? snippetFor(apiUrl, key).replace('<script ', '<script is:inline ') : snippetFor(apiUrl, key);
|
|
143
|
+
return tagChange(file, content, src, key, () => {
|
|
144
|
+
const next = insertBefore(content, /<\/head>/i, tag);
|
|
145
|
+
return next ? { content: next, lines: [`+ ${tag}`] } : null;
|
|
146
|
+
}, `${file} has no </head>. Paste the tag into the <head> of your pages yourself.`);
|
|
147
|
+
}
|
|
148
|
+
/** Matches the quote and semicolon style of the file's own imports. */
|
|
149
|
+
function importStyle(content) {
|
|
150
|
+
const imp = /^import\b.*?(['"])[^'"]+\1(;?)\s*$/m.exec(content);
|
|
151
|
+
return { q: imp?.[1] ?? "'", semi: imp?.[2] ?? '' };
|
|
152
|
+
}
|
|
153
|
+
/** Index just after the last top-level import statement (0 when there is none, after 'use client' etc.). */
|
|
154
|
+
function afterImports(content) {
|
|
155
|
+
const re = /^(?:import\b[^;]*?\bfrom\s*(['"])[^'"]+\1|import\s*(['"])[^'"]+\2)[ \t]*;?[ \t]*$/gm;
|
|
156
|
+
let end = -1;
|
|
157
|
+
for (let m = re.exec(content); m; m = re.exec(content))
|
|
158
|
+
end = m.index + m[0].length;
|
|
159
|
+
if (end >= 0)
|
|
160
|
+
return end;
|
|
161
|
+
const directive = /^(['"])use (client|server)\1;?[ \t]*$/m.exec(content);
|
|
162
|
+
return directive ? directive.index + directive[0].length : -1;
|
|
163
|
+
}
|
|
164
|
+
/** Next.js App Router: `import Script from 'next/script'` + <Script ... strategy="afterInteractive" /> before </body>. */
|
|
165
|
+
function nextLayoutChange(file, content, apiUrl, key) {
|
|
166
|
+
const src = `${apiUrl.replace(/\/+$/, '')}${SCRIPT_PATH}`;
|
|
167
|
+
return tagChange(file, content, src, key, () => {
|
|
168
|
+
const { q, semi } = importStyle(content);
|
|
169
|
+
const existing = /^import\s+(\w+)\s+from\s+['"]next\/script['"]/m.exec(content);
|
|
170
|
+
const name = existing?.[1] ?? 'Script';
|
|
171
|
+
const tag = `<${name} src="${src}" data-key="${key}" strategy="afterInteractive" />`;
|
|
172
|
+
let next = insertBefore(content, /<\/body>/, tag);
|
|
173
|
+
if (!next)
|
|
174
|
+
return null;
|
|
175
|
+
const lines = [`+ ${tag}`];
|
|
176
|
+
if (!existing) {
|
|
177
|
+
const importLine = `import ${name} from ${q}next/script${q}${semi}`;
|
|
178
|
+
const at = afterImports(next);
|
|
179
|
+
next = at < 0 ? `${importLine}\n${next}` : `${next.slice(0, at)}\n${importLine}${next.slice(at)}`;
|
|
180
|
+
lines.unshift(`+ ${importLine}`);
|
|
181
|
+
}
|
|
182
|
+
return { content: next, lines };
|
|
183
|
+
}, `${file} has no </body> this command can find. Add <Script src="${src}" data-key="${key}" strategy="afterInteractive" /> (import Script from 'next/script') inside <body> yourself.`);
|
|
184
|
+
}
|
|
185
|
+
/** Next.js Pages Router: the tag inside <Head> of pages/_document (created when missing). */
|
|
186
|
+
function nextDocumentChange(file, content, apiUrl, key) {
|
|
187
|
+
const tag = snippetFor(apiUrl, key);
|
|
188
|
+
if (content === null) {
|
|
189
|
+
const created = `import { Html, Head, Main, NextScript } from 'next/document'
|
|
190
|
+
|
|
191
|
+
export default function Document() {
|
|
192
|
+
return (
|
|
193
|
+
<Html lang="en">
|
|
194
|
+
<Head>
|
|
195
|
+
${tag}
|
|
196
|
+
</Head>
|
|
197
|
+
<body>
|
|
198
|
+
<Main />
|
|
199
|
+
<NextScript />
|
|
200
|
+
</body>
|
|
201
|
+
</Html>
|
|
202
|
+
)
|
|
203
|
+
}
|
|
204
|
+
`;
|
|
205
|
+
return { file, status: 'created', content: created, lines: [`+ ${tag}`, ' (a new file: the standard Next.js _document with the tag in <Head>)'] };
|
|
206
|
+
}
|
|
207
|
+
const src = `${apiUrl.replace(/\/+$/, '')}${SCRIPT_PATH}`;
|
|
208
|
+
return tagChange(file, content, src, key, () => {
|
|
209
|
+
let next = insertBefore(content, /<\/Head>/, tag);
|
|
210
|
+
if (!next && /<Head\s*\/>/.test(content)) {
|
|
211
|
+
const m = /^([ \t]*)<Head\s*\/>/m.exec(content);
|
|
212
|
+
const indent = m?.[1] ?? ' ';
|
|
213
|
+
next = content.replace(/<Head\s*\/>/, `<Head>\n${indent} ${tag}\n${indent}</Head>`);
|
|
214
|
+
}
|
|
215
|
+
return next ? { content: next, lines: [`+ ${tag}`] } : null;
|
|
216
|
+
}, `${file} has no <Head> this command can find. Add ${tag} inside <Head> yourself.`);
|
|
217
|
+
}
|
|
218
|
+
/** Nuxt: app.head.script in nuxt.config, when the config has no `app:` block yet. */
|
|
219
|
+
function nuxtChange(file, content, apiUrl, key) {
|
|
220
|
+
const src = `${apiUrl.replace(/\/+$/, '')}${SCRIPT_PATH}`;
|
|
221
|
+
const entry = `{ src: '${src}', defer: true, 'data-key': '${key}' }`;
|
|
222
|
+
const manual = `Add this to defineNuxtConfig({ ... }) in ${file} yourself:\n app: { head: { script: [${entry}] } },`;
|
|
223
|
+
if (EXISTING.test(content)) {
|
|
224
|
+
const next = content
|
|
225
|
+
.replace(/(['"])https?:\/\/[^'"]*\/analytics\/v1\/script\.js\1/, `'${src}'`)
|
|
226
|
+
.replace(/(['"]data-key['"]\s*:\s*)(['"])[^'"]*\2/, `$1'${key}'`);
|
|
227
|
+
if (next === content)
|
|
228
|
+
return { file, status: 'unchanged', lines: [] };
|
|
229
|
+
return { file, status: 'updated', content: next, lines: [`+ ${entry}`] };
|
|
230
|
+
}
|
|
231
|
+
const open = /defineNuxtConfig\(\s*\{/.exec(content);
|
|
232
|
+
if (!open || /^\s*app\s*:/m.test(content))
|
|
233
|
+
return { file, status: 'manual', lines: [], note: manual };
|
|
234
|
+
const at = open.index + open[0].length;
|
|
235
|
+
const rest = content.slice(at);
|
|
236
|
+
const nextLine = /\n([ \t]+)\S/.exec(rest);
|
|
237
|
+
const indent = nextLine?.[1] ?? ' ';
|
|
238
|
+
const line = `app: { head: { script: [${entry}] } },`;
|
|
239
|
+
const next = /^\s*\}/.test(rest) ? `${content.slice(0, at)}\n${indent}${line}\n${rest.replace(/^\s*/, '')}` : `${content.slice(0, at)}\n${indent}${line}${rest}`;
|
|
240
|
+
return { file, status: 'added', content: next, lines: [`+ ${line}`] };
|
|
241
|
+
}
|
|
242
|
+
/** What would change in each of the site's files. Nothing is written. */
|
|
243
|
+
export function planAnalytics(dir, site, apiUrl, key) {
|
|
244
|
+
return site.files.map((file) => {
|
|
245
|
+
const content = exists(dir, file) ? read(dir, file) : null;
|
|
246
|
+
if (site.kind === 'next') {
|
|
247
|
+
if (/\/_document\.\w+$/.test(file))
|
|
248
|
+
return nextDocumentChange(file, content, apiUrl, key);
|
|
249
|
+
return nextLayoutChange(file, content ?? '', apiUrl, key);
|
|
250
|
+
}
|
|
251
|
+
if (content === null)
|
|
252
|
+
return { file, status: 'manual', lines: [], note: `${file} was not found.` };
|
|
253
|
+
if (site.kind === 'nuxt')
|
|
254
|
+
return nuxtChange(file, content, apiUrl, key);
|
|
255
|
+
return headChange(file, content, apiUrl, key, site.kind === 'astro');
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
export function writeChanges(dir, changes) {
|
|
259
|
+
for (const ch of changes) {
|
|
260
|
+
if (ch.content === undefined || ch.status === 'unchanged' || ch.status === 'manual')
|
|
261
|
+
continue;
|
|
262
|
+
fs.mkdirSync(path.dirname(path.join(dir, ch.file)), { recursive: true });
|
|
263
|
+
fs.writeFileSync(path.join(dir, ch.file), ch.content);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/** Where to paste the tag by hand, for sites this command can't edit. */
|
|
267
|
+
function pasteHint(site) {
|
|
268
|
+
if (site.kind === 'astro')
|
|
269
|
+
return ['Paste it inside <head> in your layout (src/layouts/Layout.astro), with is:inline after <script.'];
|
|
270
|
+
if (site.kind === 'sveltekit')
|
|
271
|
+
return ['Paste it inside <head> in src/app.html.'];
|
|
272
|
+
if (site.kind === 'next')
|
|
273
|
+
return ['Paste it inside <head> of every page, or use next/script in app/layout.tsx.'];
|
|
274
|
+
return [
|
|
275
|
+
'Paste it inside <head> on every page of your website (just before </head>).',
|
|
276
|
+
`Website builders (WordPress, Wix, Webflow, Shopify, Squarespace) have a "custom code" or "header code" setting: see ${GUIDE}`,
|
|
277
|
+
];
|
|
278
|
+
}
|
|
279
|
+
const LOCAL = /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?=[:/]|$)/i;
|
|
280
|
+
export async function analyticsCommand(ctx) {
|
|
281
|
+
const { ui, cwd } = ctx;
|
|
282
|
+
ui.write(`\n${c.bold(c.magenta('usebecky'))} ${c.dim('analytics')}\n`);
|
|
283
|
+
// 1. The publishable key and the API URL.
|
|
284
|
+
let key = ctx.flags.key ?? ctx.linked.key ?? '';
|
|
285
|
+
let apiUrl = ctx.flags.apiUrl ?? ctx.linked.url ?? ctx.defaultApiUrl;
|
|
286
|
+
if (key && !ctx.flags.key && ctx.linked.file)
|
|
287
|
+
ui.info(`Using the publishable key and API URL from ${c.bold(ctx.linked.file)}`);
|
|
288
|
+
if (!key && ctx.interactive)
|
|
289
|
+
key = await ui.ask(`Your publishable key (ub_pk_..., in ${DASHBOARD_API_KEYS}):`);
|
|
290
|
+
if (/^[uy]b_sk_/.test(key)) {
|
|
291
|
+
ui.error('That is your secret key. Never put it in a website: anyone can read it there.');
|
|
292
|
+
ui.write(` ${c.dim(`Use the publishable key (ub_pk_...) from ${DASHBOARD_API_KEYS}.`)}`);
|
|
293
|
+
return 1;
|
|
294
|
+
}
|
|
295
|
+
if (!/^[uy]b_pk_\w+$/.test(key)) {
|
|
296
|
+
ui.error(key ? `"${key}" is not a publishable key (they start with ub_pk_).` : 'No publishable key found.');
|
|
297
|
+
ui.write(` ${c.dim(`Run ${c.cyan('npx usebecky init')} first, or pass --key ub_pk_... (from ${DASHBOARD_API_KEYS}).`)}`);
|
|
298
|
+
return 1;
|
|
299
|
+
}
|
|
300
|
+
apiUrl = apiUrl.trim().replace(/\/+$/, '');
|
|
301
|
+
if (!/^https?:\/\/[^\s/]+/.test(apiUrl)) {
|
|
302
|
+
ui.error(apiUrl ? `"${apiUrl}" is not a web address (it starts with https://).` : 'No API URL found.');
|
|
303
|
+
ui.write(` ${c.dim(`Pass --api-url https://... (the Project URL in ${DASHBOARD_API_KEYS}).`)}`);
|
|
304
|
+
return 1;
|
|
305
|
+
}
|
|
306
|
+
const snippet = snippetFor(apiUrl, key);
|
|
307
|
+
// 2. The website.
|
|
308
|
+
const site = detectSite(cwd);
|
|
309
|
+
if (site.kind === 'native' || site.kind === 'app') {
|
|
310
|
+
ui.info(`This folder holds ${c.bold(site.label)}. The analytics script is for websites.`);
|
|
311
|
+
ui.write(` In an app, track screens and events with the SDK instead: ${c.cyan(`${GUIDE}#use-the-sdk-in-your-apps-code`)}`);
|
|
312
|
+
ui.write(` ${c.dim('For a website that lives in another folder, run this command there.')}`);
|
|
313
|
+
return 0;
|
|
314
|
+
}
|
|
315
|
+
if (site.kind === 'unknown' || !site.files.length) {
|
|
316
|
+
ui.info(`Couldn't find where ${site.label === 'this folder' ? 'your website keeps its <head>' : `${c.bold(site.label)} keeps its <head>`}, so nothing was changed.`);
|
|
317
|
+
ui.write(`\n ${c.bold('Your analytics tag:')}\n ${c.cyan(snippet)}\n`);
|
|
318
|
+
for (const line of pasteHint(site))
|
|
319
|
+
ui.write(` ${line}`);
|
|
320
|
+
return finish(0);
|
|
321
|
+
}
|
|
322
|
+
ui.info(`Detected ${c.bold(site.label)}`);
|
|
323
|
+
// 3. The edits.
|
|
324
|
+
const changes = planAnalytics(cwd, site, apiUrl, key);
|
|
325
|
+
const dry = !!ctx.flags.dryRun;
|
|
326
|
+
for (const ch of changes) {
|
|
327
|
+
if (ch.status === 'unchanged')
|
|
328
|
+
ui.info(`${c.bold(ch.file)} already has the analytics tag`);
|
|
329
|
+
else if (ch.status === 'manual')
|
|
330
|
+
ui.warn(ch.note ?? `Couldn't change ${ch.file}.`);
|
|
331
|
+
else {
|
|
332
|
+
const verb = ch.status === 'created' ? (dry ? 'Would create' : 'Created') : ch.status === 'updated' ? (dry ? 'Would update' : 'Updated') : dry ? 'Would add the analytics tag to' : 'Added the analytics tag to';
|
|
333
|
+
ui.success(`${verb} ${c.bold(ch.file)}`);
|
|
334
|
+
for (const line of ch.lines)
|
|
335
|
+
ui.write(` ${line.startsWith('+') ? c.green(line) : line.startsWith('-') ? c.red(line) : c.dim(line)}`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (dry)
|
|
339
|
+
ui.write(`\n ${c.dim('Dry run: nothing was changed. Run it again without --dry-run to make these changes.')}`);
|
|
340
|
+
else
|
|
341
|
+
writeChanges(cwd, changes);
|
|
342
|
+
const manual = changes.filter((ch) => ch.status === 'manual');
|
|
343
|
+
if (manual.length)
|
|
344
|
+
ui.write(`\n ${c.bold('Your analytics tag:')}\n ${c.cyan(snippet)}`);
|
|
345
|
+
if (LOCAL.test(apiUrl))
|
|
346
|
+
ui.warn(`${apiUrl} is your own computer: visits from your live website can't reach it. Run this again with your hosted Project URL (--api-url) before you publish.`);
|
|
347
|
+
return finish(manual.length && manual.length === changes.length ? 1 : 0);
|
|
348
|
+
async function finish(code) {
|
|
349
|
+
const page = ctx.linked.ref && key === ctx.linked.key ? await ctx.dashboard(ctx.linked.ref).catch(() => null) : null;
|
|
350
|
+
ui.write('');
|
|
351
|
+
if (page)
|
|
352
|
+
ui.write(` Dashboard: ${c.cyan(`${page}/analytics`)}`);
|
|
353
|
+
ui.write(TURN_ON);
|
|
354
|
+
ui.write('');
|
|
355
|
+
return code;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { type Ui } from './ui.ts';
|
|
2
|
+
export declare const CONFIG_FILE: string;
|
|
3
|
+
type ApiError = {
|
|
4
|
+
code: string;
|
|
5
|
+
message: string;
|
|
6
|
+
hint?: string;
|
|
7
|
+
status: number;
|
|
8
|
+
details?: any;
|
|
9
|
+
};
|
|
10
|
+
type ApiResult<T> = {
|
|
11
|
+
data: T | null;
|
|
12
|
+
error: ApiError | null;
|
|
13
|
+
};
|
|
14
|
+
type Json = Record<string, any>;
|
|
15
|
+
export interface ConfigContext {
|
|
16
|
+
cwd: string;
|
|
17
|
+
ui: Ui;
|
|
18
|
+
/** Positional arguments after `config` (subcommand first). */
|
|
19
|
+
args: string[];
|
|
20
|
+
ref: string | null;
|
|
21
|
+
yes: boolean;
|
|
22
|
+
dryRun: boolean;
|
|
23
|
+
force: boolean;
|
|
24
|
+
env: Record<string, string | undefined>;
|
|
25
|
+
/** Platform API call for this project, already signed in: api('GET', '/auth/config'). */
|
|
26
|
+
api: <T = any>(method: string, path: string, body?: unknown) => Promise<ApiResult<T>>;
|
|
27
|
+
signIn: () => Promise<boolean>;
|
|
28
|
+
printError: (e: {
|
|
29
|
+
message: string;
|
|
30
|
+
hint?: string;
|
|
31
|
+
status?: number;
|
|
32
|
+
}) => number;
|
|
33
|
+
noProject: () => number;
|
|
34
|
+
}
|
|
35
|
+
/** Deep equality for JSON values (arrays in order, objects by key). */
|
|
36
|
+
export declare function same(a: unknown, b: unknown): boolean;
|
|
37
|
+
/** Does the project already have what the file asks for? Only the keys the file names count, also inside lists (goals
|
|
38
|
+
* written without an id); null and missing are the same. */
|
|
39
|
+
export declare function matches(want: unknown, have: unknown): boolean;
|
|
40
|
+
/** Replace every "${NAME}" string; the names without a value are collected in `missing`. */
|
|
41
|
+
export declare function resolveEnv(v: unknown, lookup: (name: string) => string | undefined, missing: Set<string>): unknown;
|
|
42
|
+
/** Check the file's shape before anything is read or changed (the server checks the values). */
|
|
43
|
+
export declare function validateConfig(file: unknown): Json;
|
|
44
|
+
/** Presets whose policies are on the bucket (storage/policies.ts names them "<bucket>: …"). */
|
|
45
|
+
export declare function presetsOf(bucket: string, policies: {
|
|
46
|
+
name: string;
|
|
47
|
+
}[]): string[];
|
|
48
|
+
export interface Step {
|
|
49
|
+
section: string;
|
|
50
|
+
/** What changes, one line each. */
|
|
51
|
+
lines: string[];
|
|
52
|
+
method: string;
|
|
53
|
+
path: string;
|
|
54
|
+
body?: unknown;
|
|
55
|
+
}
|
|
56
|
+
export interface Plan {
|
|
57
|
+
steps: Step[];
|
|
58
|
+
/** Things on the project the file doesn't name (left as they are). */
|
|
59
|
+
untouched: string[];
|
|
60
|
+
/** Sections this server doesn't have. */
|
|
61
|
+
skipped: string[];
|
|
62
|
+
/** Things worth knowing that change nothing (an archived product the file names). */
|
|
63
|
+
notes: string[];
|
|
64
|
+
}
|
|
65
|
+
/** Every change the file asks for, against what the project has now. `cfg` has its secrets resolved; `raw` is the file
|
|
66
|
+
* as written (for "from $NAME"). */
|
|
67
|
+
export declare function planConfig(ctx: ConfigContext, cfg: Json, raw: Json): Promise<Plan>;
|
|
68
|
+
/** The project's settings as a config file (secrets left out). */
|
|
69
|
+
export declare function readProjectConfig(ctx: ConfigContext): Promise<{
|
|
70
|
+
config: Json;
|
|
71
|
+
skipped: string[];
|
|
72
|
+
secrets: string[];
|
|
73
|
+
}>;
|
|
74
|
+
export declare function configCommand(ctx: ConfigContext): Promise<number>;
|
|
75
|
+
export {};
|