@usebecky/extension 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 (65) hide show
  1. package/README.md +223 -2
  2. package/dist/accounts.d.ts +85 -0
  3. package/dist/accounts.js +149 -0
  4. package/dist/cli/index.d.ts +2 -0
  5. package/dist/cli/index.js +9 -0
  6. package/dist/cli/run.d.ts +25 -0
  7. package/dist/cli/run.js +330 -0
  8. package/dist/cli/skill.d.ts +16 -0
  9. package/dist/cli/skill.js +106 -0
  10. package/dist/crypto.d.ts +12 -0
  11. package/dist/crypto.js +56 -0
  12. package/dist/dev/pages.d.ts +155 -0
  13. package/dist/dev/pages.js +243 -0
  14. package/dist/dev/plans.d.ts +45 -0
  15. package/dist/dev/plans.js +135 -0
  16. package/dist/dev/samples.d.ts +61 -0
  17. package/dist/dev/samples.js +191 -0
  18. package/dist/dev/server.d.ts +120 -0
  19. package/dist/dev/server.js +1657 -0
  20. package/dist/dev/tagging.d.ts +16 -0
  21. package/dist/dev/tagging.js +81 -0
  22. package/dist/dev/ui-render.d.ts +25 -0
  23. package/dist/dev/ui-render.js +256 -0
  24. package/dist/dev/wordmark.d.ts +1 -0
  25. package/dist/dev/wordmark.js +2 -0
  26. package/dist/errors.d.ts +98 -0
  27. package/dist/errors.js +110 -0
  28. package/dist/events.d.ts +92 -0
  29. package/dist/events.js +54 -0
  30. package/dist/extension.d.ts +214 -0
  31. package/dist/extension.js +497 -0
  32. package/dist/handlers.d.ts +39 -0
  33. package/dist/handlers.js +113 -0
  34. package/dist/identity.d.ts +99 -0
  35. package/dist/identity.js +134 -0
  36. package/dist/index.d.ts +14 -0
  37. package/dist/index.js +17 -0
  38. package/dist/jwt.d.ts +62 -0
  39. package/dist/jwt.js +152 -0
  40. package/dist/manifest.d.ts +42 -0
  41. package/dist/manifest.js +785 -0
  42. package/dist/node.d.ts +10 -0
  43. package/dist/node.js +56 -0
  44. package/dist/pkce.d.ts +9 -0
  45. package/dist/pkce.js +16 -0
  46. package/dist/stores.d.ts +100 -0
  47. package/dist/stores.js +159 -0
  48. package/dist/types.d.ts +346 -0
  49. package/dist/types.js +70 -0
  50. package/dist/ui/handler.d.ts +66 -0
  51. package/dist/ui/handler.js +105 -0
  52. package/dist/ui/schema.d.ts +423 -0
  53. package/dist/ui/schema.js +666 -0
  54. package/dist/webhooks.d.ts +26 -0
  55. package/dist/webhooks.js +99 -0
  56. package/package.json +57 -4
  57. package/skill/usebecky-extension/SKILL.md +181 -0
  58. package/skill/usebecky-extension/references/accounts.md +125 -0
  59. package/skill/usebecky-extension/references/dev-server.md +102 -0
  60. package/skill/usebecky-extension/references/manifest.md +104 -0
  61. package/skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
  62. package/skill/usebecky-extension/references/partner-api.md +87 -0
  63. package/skill/usebecky-extension/references/submit-and-pricing.md +31 -0
  64. package/skill/usebecky-extension/references/ui.md +172 -0
  65. package/skill/usebecky-extension/references/webhooks.md +97 -0
@@ -0,0 +1,785 @@
1
+ // Checks usebecky-extension.json the way usebecky checks a listing (packages/server/src/modules/extensions/listing.ts):
2
+ // first like the Developer area saves it ("Import usebecky-extension.json", then "Save draft"), then like "Submit for
3
+ // review" (listingIssues), with usebecky's own messages and field paths (`connect.redirect_uris.0`). The verdict is
4
+ // usebecky's, minus what the file can't hold: the uploaded logo and the credentials. On top of that, warnings point at
5
+ // placeholders, localhost addresses and the logo file. Pure: works in Node, browsers and edge runtimes. The CLI
6
+ // (`npx @usebecky/extension validate`) passes `fileInfo` so a relative logo path is checked on disk.
7
+ import { SUBSCRIBABLE_EVENT_TYPES } from "./events.js";
8
+ import { EXTENSION_CATEGORIES, EXTENSION_FIELD_TYPES, EXTENSION_SCOPES, LISTING_LIMITS as LIMITS, RESERVED_SLUGS } from "./types.js";
9
+ import { PAGE_ID, PLAN_ID, SETTINGS_PAGE, UI_SECTIONS } from "./ui/schema.js";
10
+ export const MANIFEST_FILE = 'usebecky-extension.json';
11
+ /** The logo upload's limit. */
12
+ export const MAX_LOGO_BYTES = 200 * 1024;
13
+ /** One problem with a field (usebecky's 400 invalid_listing with details.field). */
14
+ class Invalid extends Error {
15
+ field;
16
+ hint;
17
+ constructor(field, message, hint) {
18
+ super(message);
19
+ this.field = field;
20
+ if (hint)
21
+ this.hint = hint;
22
+ }
23
+ }
24
+ const invalid = (field, message, hint) => new Invalid(field, message, hint);
25
+ /** The fields usebecky checks, in its order. */
26
+ const TOP_KEYS = ['name', 'summary', 'description', 'category', 'publisher', 'pricing', 'links', 'connect', 'scopes', 'events', 'webhook_url', 'data_shared', 'account', 'ui'];
27
+ /** Ignored by usebecky when the file is imported (`slug` must match the extension's id). */
28
+ const IGNORED = new Set(['$schema', 'slug', 'logo_url', 'capabilities']);
29
+ const FIELD_KEYS = ['key', 'label', 'help', 'type', 'required', 'pattern', 'placeholder'];
30
+ const LINK_KEYS = ['privacy', 'dpa', 'terms', 'support', 'docs'];
31
+ const LINK_LABELS = { privacy: 'the privacy policy link', dpa: 'the data processing agreement link', terms: 'the terms link', support: 'the support link', docs: 'the documentation link' };
32
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
33
+ const LOGO_TYPES = /\.(png|svg|jpe?g)$/i;
34
+ const BLOCKED_HOST = /(^|\.)(localhost|local|internal|svc|cluster\.local)$/i;
35
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
36
+ const blank = (v) => v === undefined || v === null || (typeof v === 'string' && !v.trim());
37
+ const present = (v) => v !== undefined && v !== null && v !== '';
38
+ const cap = (s) => `${s[0].toUpperCase()}${s.slice(1)}`;
39
+ const isLoopback = (host) => host === 'localhost' || host === '127.0.0.1' || host === '[::1]';
40
+ /** URL.hostname is canonical: dotted IPv4, or IPv6 (with ":"). */
41
+ const isIp = (host) => /^\d{1,3}(\.\d{1,3}){3}$/.test(host) || host.includes(':');
42
+ function safeDecode(s) {
43
+ try {
44
+ return decodeURIComponent(s);
45
+ }
46
+ catch {
47
+ return s;
48
+ }
49
+ }
50
+ function parseUrl(v) {
51
+ try {
52
+ return new URL(v);
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ function closest(word, options) {
59
+ let best = null;
60
+ let bestD = 3;
61
+ for (const o of options) {
62
+ const d = distance(word.toLowerCase(), o.toLowerCase());
63
+ if (d < bestD)
64
+ [best, bestD] = [o, d];
65
+ }
66
+ return best;
67
+ }
68
+ function distance(a, b) {
69
+ const dp = Array.from({ length: b.length + 1 }, (_, i) => i);
70
+ for (let i = 1; i <= a.length; i++) {
71
+ let prev = dp[0];
72
+ dp[0] = i;
73
+ for (let j = 1; j <= b.length; j++) {
74
+ const tmp = dp[j];
75
+ dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
76
+ prev = tmp;
77
+ }
78
+ }
79
+ return dp[b.length];
80
+ }
81
+ /** "Did you mean ...?" in front of usebecky's hint. */
82
+ function suggest(bad, options, hint) {
83
+ const guesses = bad.map((b) => (typeof b === 'string' ? closest(b, options) : null)).filter((g) => !!g);
84
+ return guesses.length ? `Did you mean ${guesses.map((g) => `"${g}"`).join(', ')}? ${hint}` : hint;
85
+ }
86
+ // ---- usebecky's checks (listing.ts), word for word -------------------------------------------------
87
+ /** 3-40 characters a-z, 0-9 and dashes, not starting or ending with a dash; a few words are reserved. */
88
+ function checkSlug(input) {
89
+ const slug = typeof input === 'string' ? input.trim() : '';
90
+ if (!/^[a-z0-9](?:[a-z0-9-]{1,38}[a-z0-9])$/.test(slug) || slug.includes('--')) {
91
+ throw invalid('slug', 'The extension id must be 3 to 40 characters: lowercase letters, digits and single dashes.', 'Example: "cookie-banner". It is part of the address of your extension and cannot be changed later.');
92
+ }
93
+ if (RESERVED_SLUGS.includes(slug))
94
+ throw invalid('slug', `"${slug}" is reserved.`, 'Pick another id, for example your product name.');
95
+ return slug;
96
+ }
97
+ function text(field, v, max, opts) {
98
+ if (typeof v !== 'string')
99
+ throw invalid(field, `${opts.label} must be text.`);
100
+ const s = v.trim();
101
+ if (!s.length)
102
+ throw invalid(field, `${opts.label} can't be empty.`);
103
+ if (s.length < (opts.min ?? 1))
104
+ throw invalid(field, `${opts.label} is too short (at least ${opts.min} characters).`);
105
+ if (s.length > max)
106
+ throw invalid(field, `${opts.label} is too long (${s.length} characters, at most ${max}).`);
107
+ return s;
108
+ }
109
+ /** An absolute https URL (http only for loopback addresses when `loopbackHttp`). No username/password or fragment. */
110
+ function checkUrl(field, v, label, opts = {}) {
111
+ if (typeof v !== 'string' || !v.trim())
112
+ throw invalid(field, `Enter ${label}, starting with https://`);
113
+ const raw = v.trim();
114
+ if (raw.length > LIMITS.url)
115
+ throw invalid(field, `${cap(label)} is too long (at most ${LIMITS.url} characters).`);
116
+ const u = parseUrl(raw);
117
+ if (!u)
118
+ throw invalid(field, `"${raw.slice(0, 80)}" is not a full web address.`, 'Use the full address, like https://example.com/privacy');
119
+ if (opts.mailto && u.protocol === 'mailto:' && EMAIL.test(safeDecode(u.pathname)))
120
+ return raw;
121
+ const httpOk = opts.loopbackHttp && u.protocol === 'http:' && isLoopback(u.hostname);
122
+ if (u.protocol !== 'https:' && !httpOk)
123
+ throw invalid(field, `${cap(label)} must start with https://`, opts.loopbackHttp ? 'Plain http is only allowed for http://localhost while you test.' : undefined);
124
+ if (u.username || u.password)
125
+ throw invalid(field, `Don't put a username or password in ${label}.`);
126
+ if (u.hash)
127
+ throw invalid(field, `${cap(label)} can't contain a "#" part.`);
128
+ return raw;
129
+ }
130
+ const WEBHOOK_WORDS = {
131
+ label: 'the webhook address',
132
+ endpoint: 'your webhook endpoint',
133
+ example: 'https://example.com/usebecky/webhook',
134
+ why: 'usebecky only sends events over https, so nobody can read or change them on the way.',
135
+ };
136
+ const PROVISION_WORDS = {
137
+ label: 'the provision address',
138
+ endpoint: 'your provision endpoint',
139
+ example: 'https://example.com/usebecky/provision',
140
+ why: "usebecky sends your customers' names and email addresses there, so only over https.",
141
+ };
142
+ /** https and a public host name, unless `allowPrivate` (a local usebecky, the dev server). */
143
+ function checkServerUrl(field, v, allowPrivate, w) {
144
+ const Label = cap(w.label);
145
+ if (typeof v !== 'string' || !v.trim())
146
+ throw invalid(field, `Enter the address of ${w.endpoint}, starting with https://`);
147
+ const raw = v.trim();
148
+ if (raw.length > LIMITS.url)
149
+ throw invalid(field, `${Label} is too long (at most ${LIMITS.url} characters).`);
150
+ const u = parseUrl(raw);
151
+ if (!u)
152
+ throw invalid(field, `"${raw.slice(0, 80)}" is not a full web address.`, `Use the full address, like ${w.example}`);
153
+ if (u.protocol !== 'https:' && !(allowPrivate && u.protocol === 'http:'))
154
+ throw invalid(field, `${Label} must start with https://`, w.why);
155
+ if (u.username || u.password)
156
+ throw invalid(field, `Don't put a username or password in ${w.label}.`, 'Check the usebecky-signature header on your server instead.');
157
+ if (u.hash)
158
+ throw invalid(field, `${Label} can't contain a "#" part.`);
159
+ if (!allowPrivate) {
160
+ const host = u.hostname.replace(/^\[|\]$/g, '');
161
+ if (isIp(host) || BLOCKED_HOST.test(host))
162
+ throw invalid(field, `${Label} must use a public host name.`, `Use your server's domain name, like ${w.example.replace('https://example.com', 'https://api.example.com')}. IP addresses and local names are not allowed.`);
163
+ }
164
+ return raw;
165
+ }
166
+ const checkWebhookUrl = (field, v, allowPrivate) => checkServerUrl(field, v, allowPrivate, WEBHOOK_WORDS);
167
+ const checkProvisionUrl = (field, v, allowPrivate) => checkServerUrl(field, v, allowPrivate, PROVISION_WORDS);
168
+ const UI_WORDS = {
169
+ label: 'the UI address',
170
+ endpoint: 'your UI endpoint',
171
+ example: 'https://example.com/usebecky/ui',
172
+ why: 'usebecky sends who is looking at your pages and what they type there, so only over https.',
173
+ };
174
+ const checkUiUrl = (field, v, allowPrivate) => checkServerUrl(field, v, allowPrivate, UI_WORDS);
175
+ const UI_KEYS = ['url', 'pages', 'settings'];
176
+ const UI_PAGE_KEYS = ['id', 'label', 'section'];
177
+ const UI_NEEDS_A_PAGE = 'Add at least one page for the sidebar (ui.pages) or the settings view ("settings": true).';
178
+ function uiKeys(o) {
179
+ for (const k of Object.keys(o))
180
+ if (!UI_KEYS.includes(k))
181
+ throw invalid(`ui.${k}`, `Unknown ui property "${k}".`, 'Use url, pages and settings.');
182
+ }
183
+ function uiPage(field, p, seen) {
184
+ if (!isObj(p))
185
+ throw invalid(field, 'Each page must be an object like {"id": "reviews", "label": "Reviews", "section": "website"}.');
186
+ for (const k of Object.keys(p))
187
+ if (!UI_PAGE_KEYS.includes(k))
188
+ throw invalid(`${field}.${k}`, `Unknown page property "${k}".`, 'Use id, label and section.');
189
+ const id = typeof p.id === 'string' ? p.id.trim() : '';
190
+ if (id === SETTINGS_PAGE)
191
+ throw invalid(`${field}.id`, '"settings" is reserved for the view on your extension\'s page.', 'Use "settings": true for that view, and another id for a sidebar page.');
192
+ if (!PAGE_ID.test(id))
193
+ throw invalid(`${field}.id`, 'A page id must be 1 to 32 characters: lowercase letters, digits and dashes, starting with a letter.', 'Example: "reviews". It is part of the page\'s address in usebecky.');
194
+ if (seen.has(id))
195
+ throw invalid(`${field}.id`, `Two pages use the id "${id}".`);
196
+ seen.add(id);
197
+ const label = text(`${field}.label`, p.label, LIMITS.uiLabel, { label: 'The page label' });
198
+ const section = blank(p.section) ? 'project' : p.section;
199
+ if (!UI_SECTIONS.includes(section))
200
+ throw invalid(`${field}.section`, `The section must be one of: ${UI_SECTIONS.join(', ')}.`, 'It is the sidebar group the page shows in: backend, website (Website & sales), messages or project.');
201
+ return { id, label, section: section };
202
+ }
203
+ function uiPages(v, dropBlank = false) {
204
+ if (v === undefined || v === null)
205
+ return [];
206
+ if (!Array.isArray(v))
207
+ throw invalid('ui.pages', 'ui.pages must be a list like [{"id": "reviews", "label": "Reviews", "section": "website"}].');
208
+ const rows = dropBlank ? v.filter((p) => !(isObj(p) && blank(p.id) && blank(p.label))) : v;
209
+ if (rows.length > LIMITS.uiPages)
210
+ throw invalid('ui.pages', `At most ${LIMITS.uiPages} pages in the sidebar.`, 'Put more inside one page, with tabs.');
211
+ const seen = new Set();
212
+ return rows.map((p, i) => uiPage(`ui.pages.${i}`, p, seen));
213
+ }
214
+ function uiSettings(v, out) {
215
+ if (v === undefined || v === null)
216
+ return;
217
+ if (typeof v !== 'boolean')
218
+ throw invalid('ui.settings', 'ui.settings must be true or false.');
219
+ if (v)
220
+ out.settings = true;
221
+ }
222
+ function checkUi(v, allowPrivate) {
223
+ if (!isObj(v))
224
+ throw invalid('ui', 'ui must be an object like {"url": "https://...", "pages": [{"id": "reviews", "label": "Reviews"}]}.');
225
+ uiKeys(v);
226
+ const out = { url: checkUiUrl('ui.url', v.url, allowPrivate) };
227
+ const pages = uiPages(v.pages);
228
+ if (pages.length)
229
+ out.pages = pages;
230
+ uiSettings(v.settings, out);
231
+ if (!pages.length && !out.settings)
232
+ throw invalid('ui.pages', UI_NEEDS_A_PAGE, 'Or remove ui if the extension shows nothing inside usebecky.');
233
+ return out;
234
+ }
235
+ function uiBeingFilled(v) {
236
+ if (!isObj(v))
237
+ return false;
238
+ return blank(v.url) || (!(Array.isArray(v.pages) && v.pages.length) && v.settings !== true);
239
+ }
240
+ const ACCOUNT_KEYS = ['required', 'provision', 'provision_url', 'sso_url', 'members_can_open'];
241
+ const PROVISION_HINT = 'Customers never sign up at your service by hand: usebecky gives you their name and email so you create the account.';
242
+ const PROVISION_URL_ONLY = 'With "oauth", create the account from the id_token in your OAuth callback.';
243
+ function accountKeys(o) {
244
+ for (const k of Object.keys(o))
245
+ if (!ACCOUNT_KEYS.includes(k))
246
+ throw invalid(`account.${k}`, `Unknown account property "${k}".`, suggest([k], ACCOUNT_KEYS, 'Use required, provision, provision_url, sso_url and members_can_open.'));
247
+ if (typeof o.required !== 'boolean')
248
+ throw invalid('account.required', 'Say whether customers need an account at your service: "required": true or false.');
249
+ }
250
+ function accountProvision(v) {
251
+ if (v !== 'oauth' && v !== 'url')
252
+ throw invalid('account.provision', 'account.provision must be "oauth" (accounts from the sign-in id_token) or "url" (usebecky calls your provision URL).', PROVISION_HINT);
253
+ return v;
254
+ }
255
+ function accountMembers(v, out) {
256
+ if (v === undefined || v === null)
257
+ return;
258
+ if (typeof v !== 'boolean')
259
+ throw invalid('account.members_can_open', 'members_can_open must be true or false.');
260
+ if (v)
261
+ out.members_can_open = true;
262
+ }
263
+ /** The account field, complete. */
264
+ function checkAccount(v, allowPrivate) {
265
+ if (!isObj(v))
266
+ throw invalid('account', 'account must be {"required": false} or {"required": true, "provision": "oauth", "sso_url": "https://..."}.');
267
+ accountKeys(v);
268
+ if (!v.required) {
269
+ for (const k of ACCOUNT_KEYS.slice(1))
270
+ if (present(v[k]))
271
+ throw invalid(`account.${k}`, `"${k}" only applies when customers need an account ("required": true).`);
272
+ return { required: false };
273
+ }
274
+ const provision = accountProvision(v.provision);
275
+ const out = { required: true, provision };
276
+ if (provision === 'url')
277
+ out.provision_url = checkProvisionUrl('account.provision_url', v.provision_url, allowPrivate);
278
+ else if (present(v.provision_url))
279
+ throw invalid('account.provision_url', 'provision_url is only used with "provision": "url".', PROVISION_URL_ONLY);
280
+ out.sso_url = checkUrl('account.sso_url', v.sso_url, 'the single sign-on URL', { loopbackHttp: true });
281
+ accountMembers(v.members_can_open, out);
282
+ return out;
283
+ }
284
+ /** account.required with a part still missing (usebecky lists the parts one by one). */
285
+ function accountBeingFilled(v) {
286
+ return isObj(v) && v.required === true && (!v.provision || !v.sso_url || (v.provision === 'url' && !v.provision_url));
287
+ }
288
+ function checkField(field, f, seen) {
289
+ if (!isObj(f))
290
+ throw invalid(field, 'Each settings field must be an object like {"key": "site_id", "label": "Site ID", "type": "text", "required": true}.');
291
+ for (const k of Object.keys(f))
292
+ if (!FIELD_KEYS.includes(k))
293
+ throw invalid(`${field}.${k}`, `Unknown settings field property "${k}".`, 'Use key, label, help, type, required, pattern and placeholder.');
294
+ const key = typeof f.key === 'string' ? f.key.trim() : '';
295
+ if (!/^[a-z][a-z0-9_]{0,39}$/.test(key))
296
+ throw invalid(`${field}.key`, 'A settings field key must be 1 to 40 characters: lowercase letters, digits and underscores, starting with a letter.', 'Example: "site_id".');
297
+ if (seen.has(key))
298
+ throw invalid(`${field}.key`, `Two settings fields use the key "${key}".`);
299
+ seen.add(key);
300
+ if (!EXTENSION_FIELD_TYPES.includes(f.type))
301
+ throw invalid(`${field}.type`, 'A settings field type must be "text", "url", "secret" or "boolean".');
302
+ if (typeof f.required !== 'boolean')
303
+ throw invalid(`${field}.required`, 'Say whether the field is required: "required": true or false.');
304
+ const out = { key, label: text(`${field}.label`, f.label, LIMITS.fieldLabel, { label: 'The field label' }), type: f.type, required: f.required };
305
+ if (present(f.help))
306
+ out.help = text(`${field}.help`, f.help, LIMITS.fieldHelp, { label: 'The help text' });
307
+ if (out.type === 'boolean') {
308
+ // A yes/no checkbox: its value is true or false, so there is nothing to type and nothing to match.
309
+ if (present(f.placeholder))
310
+ throw invalid(`${field}.placeholder`, 'A yes/no field has no placeholder.', 'Remove "placeholder": customers see a checkbox.');
311
+ if (present(f.pattern))
312
+ throw invalid(`${field}.pattern`, 'A yes/no field has no pattern.', 'Remove "pattern": the value is true or false.');
313
+ return out;
314
+ }
315
+ if (present(f.placeholder))
316
+ out.placeholder = text(`${field}.placeholder`, f.placeholder, LIMITS.fieldPlaceholder, { label: 'The placeholder' });
317
+ if (present(f.pattern)) {
318
+ const p = text(`${field}.pattern`, f.pattern, LIMITS.pattern, { label: 'The pattern' });
319
+ try {
320
+ new RegExp(p, 'u');
321
+ }
322
+ catch {
323
+ throw invalid(`${field}.pattern`, `The pattern of "${key}" is not a valid regular expression.`, 'Example: ^[A-Z0-9]{8}$');
324
+ }
325
+ out.pattern = p;
326
+ }
327
+ return out;
328
+ }
329
+ const PLAN_KEYS = ['id', 'name', 'amount', 'summary'];
330
+ /** One plan of pricing "plans". */
331
+ function checkPlan(field, p, seen) {
332
+ if (!isObj(p))
333
+ throw invalid(field, 'Each plan must be an object like {"id": "pro", "name": "Pro", "amount": 2900, "summary": "For growing shops"}.');
334
+ for (const k of Object.keys(p))
335
+ if (!PLAN_KEYS.includes(k))
336
+ throw invalid(`${field}.${k}`, `Unknown plan property "${k}".`, 'Use id, name, amount and summary.');
337
+ const id = typeof p.id === 'string' ? p.id.trim() : '';
338
+ if (!PLAN_ID.test(id))
339
+ throw invalid(`${field}.id`, 'A plan id must be 1 to 30 characters: lowercase letters, digits and dashes.', 'Example: "pro". Your extension recognises the plan by it, so keep it when you change the price.');
340
+ if (seen.has(id))
341
+ throw invalid(`${field}.id`, `Two plans use the id "${id}".`);
342
+ seen.add(id);
343
+ const name = text(`${field}.name`, p.name, LIMITS.planName, { label: 'The plan name' });
344
+ if (!Number.isInteger(p.amount) || p.amount < LIMITS.priceMin || p.amount > LIMITS.priceMax)
345
+ throw invalid(`${field}.amount`, `The monthly price must be a whole number of US cents from ${LIMITS.priceMin} (${LIMITS.priceMin / 100} USD) to ${LIMITS.priceMax} (${LIMITS.priceMax / 100} USD).`, 'Example: 900 for 9 USD per project and month.');
346
+ const out = { id, name, amount: p.amount };
347
+ if (!blank(p.summary))
348
+ out.summary = text(`${field}.summary`, p.summary, LIMITS.planSummary, { label: 'The plan summary' });
349
+ return out;
350
+ }
351
+ /** pricing.plans; rows left completely empty (an editor's blank row) are dropped when `dropBlank`. */
352
+ function checkPlans(v, dropBlank = false) {
353
+ if (!Array.isArray(v))
354
+ throw invalid('pricing.plans', 'Plans must be a list like [{"id": "basic", "name": "Basic", "amount": 900}, {"id": "pro", "name": "Pro", "amount": 2900}].');
355
+ const isBlankRow = (p) => isObj(p) && ['id', 'name', 'amount', 'summary'].every((k) => blank(p[k]));
356
+ const rows = dropBlank ? v.filter((p) => !isBlankRow(p)) : v;
357
+ if (rows.length > LIMITS.plansMax)
358
+ throw invalid('pricing.plans', `At most ${LIMITS.plansMax} plans.`, 'Fewer plans are easier to choose from.');
359
+ const seen = new Set();
360
+ return rows.map((p, i) => checkPlan(`pricing.plans.${i}`, p, seen));
361
+ }
362
+ function trialDays(v) {
363
+ const trial = v === undefined || v === null ? 0 : v;
364
+ if (!Number.isInteger(trial) || trial < 0 || trial > LIMITS.trialDaysMax)
365
+ throw invalid('pricing.trial_days', `The free trial must be 0 to ${LIMITS.trialDaysMax} days.`);
366
+ return trial;
367
+ }
368
+ /** One top-level listing field. Returns the normalised value. */
369
+ function checkTopField(key, v, allowPrivate) {
370
+ switch (key) {
371
+ case 'name':
372
+ return text('name', v, LIMITS.name, { min: LIMITS.nameMin, label: 'The name' });
373
+ case 'summary':
374
+ return text('summary', v, LIMITS.summary, { label: 'The summary' });
375
+ case 'description':
376
+ return text('description', v, LIMITS.description, { label: 'The description' });
377
+ case 'category':
378
+ if (!EXTENSION_CATEGORIES.includes(v))
379
+ throw invalid('category', `The category must be one of: ${EXTENSION_CATEGORIES.join(', ')}.`);
380
+ return v;
381
+ case 'publisher': {
382
+ if (!isObj(v))
383
+ throw invalid('publisher', 'The publisher must be an object like {"name": "Acme GmbH", "website": "https://acme.com", "email": "hello@acme.com"}.');
384
+ for (const k of Object.keys(v))
385
+ if (!['name', 'website', 'email'].includes(k))
386
+ throw invalid(`publisher.${k}`, `Unknown publisher property "${k}".`);
387
+ const email = text('publisher.email', v.email, 200, { label: 'The publisher email' });
388
+ if (!EMAIL.test(email))
389
+ throw invalid('publisher.email', 'Enter a valid email address for the publisher.');
390
+ return { name: text('publisher.name', v.name, 80, { label: 'The publisher name' }), website: checkUrl('publisher.website', v.website, "the publisher's website"), email };
391
+ }
392
+ case 'pricing': {
393
+ if (!isObj(v))
394
+ throw invalid('pricing', 'Pricing must be {"model": "free"} or {"model": "monthly", "amount": 900, "trial_days": 14}.');
395
+ if (v.model === 'free')
396
+ return { model: 'free' };
397
+ if (v.model === 'plans') {
398
+ const plans = checkPlans(v.plans);
399
+ if (plans.length < LIMITS.plansMin)
400
+ throw invalid('pricing.plans', `Offer at least ${LIMITS.plansMin} plans, or one monthly price instead.`, 'Example: [{"id": "basic", "name": "Basic", "amount": 900}, {"id": "pro", "name": "Pro", "amount": 2900}].');
401
+ return { model: 'plans', trial_days: trialDays(v.trial_days), plans };
402
+ }
403
+ if (v.model !== 'monthly')
404
+ throw invalid('pricing.model', 'The pricing model must be "free", "monthly" or "plans".');
405
+ const amount = v.amount;
406
+ if (!Number.isInteger(amount) || amount < LIMITS.priceMin || amount > LIMITS.priceMax)
407
+ throw invalid('pricing.amount', `The monthly price must be a whole number of US cents from ${LIMITS.priceMin} (${LIMITS.priceMin / 100} USD) to ${LIMITS.priceMax} (${LIMITS.priceMax / 100} USD).`, 'Example: 900 for 9 USD per project and month.');
408
+ return { model: 'monthly', amount, trial_days: trialDays(v.trial_days) };
409
+ }
410
+ case 'links': {
411
+ if (!isObj(v))
412
+ throw invalid('links', 'Links must be an object like {"privacy": "https://...", "support": "https://..."}.');
413
+ const out = {};
414
+ for (const k of Object.keys(v)) {
415
+ if (!LINK_KEYS.includes(k))
416
+ throw invalid(`links.${k}`, `Unknown link "${k}".`, suggest([k], LINK_KEYS, 'Use privacy, dpa, terms, support and docs.'));
417
+ if (v[k] === null || v[k] === '')
418
+ continue;
419
+ out[k] = checkUrl(`links.${k}`, v[k], LINK_LABELS[k], { mailto: k === 'support' });
420
+ }
421
+ return out;
422
+ }
423
+ case 'connect': {
424
+ if (!isObj(v))
425
+ throw invalid('connect', 'connect must be {"mode": "oauth", "install_url", "redirect_uris"} or {"mode": "fields", "fields": [...]}.');
426
+ if (v.mode === 'oauth') {
427
+ for (const k of Object.keys(v))
428
+ if (!['mode', 'install_url', 'redirect_uris'].includes(k))
429
+ throw invalid(`connect.${k}`, `Unknown property "${k}" for connect mode "oauth".`);
430
+ const install = checkUrl('connect.install_url', v.install_url, 'the install link', { loopbackHttp: true });
431
+ if (!Array.isArray(v.redirect_uris) || !v.redirect_uris.length)
432
+ throw invalid('connect.redirect_uris', 'Add at least one redirect URI: the exact address usebecky sends people back to after they allow access.');
433
+ if (v.redirect_uris.length > LIMITS.redirectUris)
434
+ throw invalid('connect.redirect_uris', `At most ${LIMITS.redirectUris} redirect URIs.`);
435
+ const uris = v.redirect_uris.map((u, i) => checkUrl(`connect.redirect_uris.${i}`, u, 'the redirect URI', { loopbackHttp: true }));
436
+ if (new Set(uris).size !== uris.length)
437
+ throw invalid('connect.redirect_uris', 'A redirect URI is listed twice.');
438
+ return { mode: 'oauth', install_url: install, redirect_uris: uris };
439
+ }
440
+ if (v.mode === 'fields') {
441
+ for (const k of Object.keys(v))
442
+ if (!['mode', 'fields'].includes(k))
443
+ throw invalid(`connect.${k}`, `Unknown property "${k}" for connect mode "fields".`);
444
+ if (!Array.isArray(v.fields) || !v.fields.length)
445
+ throw invalid('connect.fields', 'Add at least one settings field the customer fills in.');
446
+ if (v.fields.length > LIMITS.fields)
447
+ throw invalid('connect.fields', `At most ${LIMITS.fields} settings fields.`);
448
+ const seen = new Set();
449
+ return { mode: 'fields', fields: v.fields.map((f, i) => checkField(`connect.fields.${i}`, f, seen)) };
450
+ }
451
+ throw invalid('connect.mode', 'connect.mode must be "oauth" (people connect from your website) or "fields" (people fill in settings in usebecky).');
452
+ }
453
+ case 'scopes': {
454
+ if (!Array.isArray(v))
455
+ throw invalid('scopes', `Scopes must be a list, from: ${EXTENSION_SCOPES.join(', ')}.`);
456
+ const bad = v.filter((s) => !EXTENSION_SCOPES.includes(s));
457
+ if (bad.length)
458
+ throw invalid('scopes', `Unknown scope: ${bad.map(String).join(', ')}.`, suggest(bad, EXTENSION_SCOPES, `Use: ${EXTENSION_SCOPES.join(', ')}.`));
459
+ return [...new Set(v)];
460
+ }
461
+ case 'events': {
462
+ if (!Array.isArray(v))
463
+ throw invalid('events', 'Events must be a list of event types, like ["user.created", "purchase.completed"].');
464
+ const bad = v.filter((t) => !SUBSCRIBABLE_EVENT_TYPES.includes(t));
465
+ if (bad.length)
466
+ throw invalid('events', `Unknown event type: ${bad.map(String).join(', ')}.`, suggest(bad, SUBSCRIBABLE_EVENT_TYPES, 'extension.installed and extension.uninstalled are always sent; see the event list in the API reference.'));
467
+ return [...new Set(v)];
468
+ }
469
+ case 'webhook_url':
470
+ return checkWebhookUrl('webhook_url', v, allowPrivate);
471
+ case 'account':
472
+ return checkAccount(v, allowPrivate);
473
+ case 'ui':
474
+ return checkUi(v, allowPrivate);
475
+ case 'data_shared': {
476
+ if (!Array.isArray(v))
477
+ throw invalid('data_shared', 'data_shared must be a list of short sentences, like ["Purchases: amount, currency and product"].');
478
+ if (v.length > LIMITS.dataShared)
479
+ throw invalid('data_shared', `At most ${LIMITS.dataShared} lines.`);
480
+ return v.map((s, i) => text(`data_shared.${i}`, s, LIMITS.dataSharedItem, { label: 'Each line' }));
481
+ }
482
+ default:
483
+ throw invalid(key, `Unknown listing field "${key}".`, suggest([key], [...TOP_KEYS, ...IGNORED], 'See the listing fields in the API reference (Extensions).'));
484
+ }
485
+ }
486
+ /** A half-filled part, as "Save draft" keeps it: empty parts are left out (asked for before review), the rest is checked. */
487
+ function draftValue(key, v, allowPrivate) {
488
+ if (!isObj(v))
489
+ return checkTopField(key, v, allowPrivate);
490
+ if (key === 'publisher') {
491
+ for (const k of Object.keys(v))
492
+ if (!['name', 'website', 'email'].includes(k))
493
+ throw invalid(`publisher.${k}`, `Unknown publisher property "${k}".`);
494
+ const out = {};
495
+ if (!blank(v.name))
496
+ out.name = text('publisher.name', v.name, 80, { label: 'The publisher name' });
497
+ if (!blank(v.website))
498
+ out.website = checkUrl('publisher.website', v.website, "the publisher's website");
499
+ if (!blank(v.email)) {
500
+ const email = text('publisher.email', v.email, 200, { label: 'The publisher email' });
501
+ if (!EMAIL.test(email))
502
+ throw invalid('publisher.email', 'Enter a valid email address for the publisher.');
503
+ out.email = email;
504
+ }
505
+ return Object.keys(out).length ? out : undefined;
506
+ }
507
+ if (key === 'connect' && v.mode === 'oauth') {
508
+ for (const k of Object.keys(v))
509
+ if (!['mode', 'install_url', 'redirect_uris'].includes(k))
510
+ throw invalid(`connect.${k}`, `Unknown property "${k}" for connect mode "oauth".`);
511
+ const uris = v.redirect_uris === undefined || v.redirect_uris === null ? [] : v.redirect_uris;
512
+ if (!Array.isArray(uris))
513
+ throw invalid('connect.redirect_uris', 'redirect_uris must be a list of addresses.');
514
+ const filled = uris.filter((u) => !blank(u));
515
+ if (filled.length > LIMITS.redirectUris)
516
+ throw invalid('connect.redirect_uris', `At most ${LIMITS.redirectUris} redirect URIs.`);
517
+ const checked = filled.map((u, i) => checkUrl(`connect.redirect_uris.${i}`, u, 'the redirect URI', { loopbackHttp: true }));
518
+ if (new Set(checked).size !== checked.length)
519
+ throw invalid('connect.redirect_uris', 'A redirect URI is listed twice.');
520
+ const out = { mode: 'oauth', redirect_uris: checked };
521
+ if (!blank(v.install_url))
522
+ out.install_url = checkUrl('connect.install_url', v.install_url, 'the install link', { loopbackHttp: true });
523
+ return out;
524
+ }
525
+ if (key === 'connect' && v.mode === 'fields' && Array.isArray(v.fields) && !v.fields.length) {
526
+ for (const k of Object.keys(v))
527
+ if (!['mode', 'fields'].includes(k))
528
+ throw invalid(`connect.${k}`, `Unknown property "${k}" for connect mode "fields".`);
529
+ return { mode: 'fields', fields: [] };
530
+ }
531
+ if (key === 'account' && v.required === true) {
532
+ accountKeys(v);
533
+ const out = { required: true };
534
+ if (!blank(v.provision))
535
+ out.provision = accountProvision(v.provision);
536
+ if (!blank(v.provision_url)) {
537
+ if (out.provision === 'oauth')
538
+ throw invalid('account.provision_url', 'provision_url is only used with "provision": "url".', PROVISION_URL_ONLY);
539
+ out.provision_url = checkProvisionUrl('account.provision_url', v.provision_url, allowPrivate);
540
+ }
541
+ if (!blank(v.sso_url))
542
+ out.sso_url = checkUrl('account.sso_url', v.sso_url, 'the single sign-on URL', { loopbackHttp: true });
543
+ accountMembers(v.members_can_open, out);
544
+ return out;
545
+ }
546
+ if (key === 'ui') {
547
+ uiKeys(v);
548
+ const out = {};
549
+ if (!blank(v.url))
550
+ out.url = checkUiUrl('ui.url', v.url, allowPrivate);
551
+ const pages = uiPages(v.pages, true);
552
+ if (pages.length)
553
+ out.pages = pages;
554
+ uiSettings(v.settings, out);
555
+ // Kept even when empty, like usebecky: the address and a page are asked for below.
556
+ return out;
557
+ }
558
+ if (key === 'pricing' && v.model === 'monthly' && (blank(v.amount) || v.amount === 0)) {
559
+ const trial = blank(v.trial_days) ? 0 : v.trial_days;
560
+ if (!Number.isInteger(trial) || trial < 0 || trial > LIMITS.trialDaysMax)
561
+ throw invalid('pricing.trial_days', `The free trial must be 0 to ${LIMITS.trialDaysMax} days.`);
562
+ return { model: 'monthly', trial_days: trial };
563
+ }
564
+ if (key === 'pricing' && v.model === 'plans') {
565
+ // Being filled in: blank plan rows are dropped, fewer than two plans are asked for on submit.
566
+ const trial = blank(v.trial_days) ? 0 : v.trial_days;
567
+ if (!Number.isInteger(trial) || trial < 0 || trial > LIMITS.trialDaysMax)
568
+ throw invalid('pricing.trial_days', `The free trial must be 0 to ${LIMITS.trialDaysMax} days.`);
569
+ return { model: 'plans', trial_days: trial, plans: v.plans === undefined || v.plans === null ? [] : checkPlans(v.plans, true) };
570
+ }
571
+ return checkTopField(key, v, allowPrivate);
572
+ }
573
+ // ---- validateManifest ----------------------------------------------------------------------------
574
+ /** Check a parsed usebecky-extension.json. */
575
+ export function validateManifest(input, options = {}) {
576
+ const errors = [];
577
+ const warnings = [];
578
+ const issue = (path, message, hint) => (hint ? { path, message, hint } : { path, message });
579
+ const warn = (path, message, hint) => warnings.push(issue(path, message, hint));
580
+ if (!isObj(input)) {
581
+ errors.push(issue('', 'The file must hold one JSON object: { "slug": "...", "name": "...", ... }.'));
582
+ return { ok: false, errors, warnings, manifest: null };
583
+ }
584
+ const m = input;
585
+ const allowPrivate = !!options.allowPrivateWebhookUrl;
586
+ /** Top-level fields with an error: what is "missing" about them isn't reported on top. */
587
+ const failed = new Set();
588
+ const fail = (key, e) => {
589
+ if (!(e instanceof Invalid))
590
+ throw e;
591
+ errors.push(issue(e.field, e.message, e.hint));
592
+ failed.add(key);
593
+ };
594
+ // The id: chosen when the extension is created in the Developer area. usebecky refuses a file with another one.
595
+ if (blank(m.slug))
596
+ warn('slug', 'There is no "slug". Add the id you chose when you created the extension in the Developer area: the dev server and the CLI use it, and usebecky refuses a file with another id.');
597
+ else
598
+ try {
599
+ checkSlug(m.slug);
600
+ }
601
+ catch (e) {
602
+ fail('slug', e);
603
+ }
604
+ // 1. "Save draft": every field the file has (null or "" clears it), a half-filled publisher, connect or price kept.
605
+ const draft = {};
606
+ for (const [key, value] of Object.entries(m)) {
607
+ if (IGNORED.has(key) || value === undefined)
608
+ continue;
609
+ if (value === null || value === '') {
610
+ if (key === 'name')
611
+ fail('name', invalid('name', "The name can't be empty."));
612
+ continue;
613
+ }
614
+ try {
615
+ const checked = draftValue(key, value, allowPrivate);
616
+ if (checked !== undefined)
617
+ draft[key] = checked;
618
+ }
619
+ catch (e) {
620
+ fail(key, e);
621
+ }
622
+ }
623
+ // 2. "Submit for review": every saved field again, then what is still missing.
624
+ for (const key of TOP_KEYS) {
625
+ if (draft[key] === undefined || failed.has(key))
626
+ continue;
627
+ if (key === 'account' && accountBeingFilled(draft.account))
628
+ continue;
629
+ if (key === 'ui' && uiBeingFilled(draft.ui))
630
+ continue;
631
+ try {
632
+ checkTopField(key, draft[key], allowPrivate);
633
+ }
634
+ catch (e) {
635
+ fail(key, e);
636
+ }
637
+ }
638
+ const d = draft;
639
+ const need = (keys, field, message) => {
640
+ if (!keys.some((k) => failed.has(k)))
641
+ errors.push(issue(field, message));
642
+ };
643
+ if (!d.name)
644
+ need(['name'], 'name', 'Give the extension a name.');
645
+ if (!d.summary)
646
+ need(['summary'], 'summary', `Write a one-line summary (at most ${LIMITS.summary} characters).`);
647
+ if (!d.description)
648
+ need(['description'], 'description', 'Describe what the extension does for the customer.');
649
+ if (!d.category)
650
+ need(['category'], 'category', 'Pick a category.');
651
+ if (!d.publisher)
652
+ need(['publisher'], 'publisher', 'Add the publisher: name, website and email.');
653
+ if (!d.pricing)
654
+ need(['pricing'], 'pricing', 'Choose free, one monthly price or plans.');
655
+ if (!d.links?.privacy)
656
+ need(['links'], 'links.privacy', 'Add a link to your privacy policy.');
657
+ if (!d.links?.support)
658
+ need(['links'], 'links.support', 'Add a support link or email address (mailto:).');
659
+ if (!d.connect)
660
+ need(['connect'], 'connect', 'Choose how customers connect: through your website (oauth) or by filling in settings (fields).');
661
+ if (!d.scopes)
662
+ need(['scopes'], 'scopes', 'Choose the permissions the extension needs (an empty list is fine).');
663
+ if (!d.data_shared?.length)
664
+ need(['data_shared'], 'data_shared', 'List in plain words what data the extension gets, for the consent screen.');
665
+ const events = d.events ?? [];
666
+ if (events.length && !d.scopes?.includes('events:read'))
667
+ need(['events', 'scopes'], 'events', 'Receiving events needs the "events:read" permission.');
668
+ if (events.length && !d.webhook_url)
669
+ need(['events', 'webhook_url'], 'webhook_url', 'Add a webhook address to receive the events.');
670
+ if (d.scopes?.includes('events:read') && !events.length)
671
+ need(['events', 'scopes'], 'events', 'Pick the events the extension receives, or remove the "events:read" permission.');
672
+ const account = d.account;
673
+ if (account?.required === true) {
674
+ // The rule: customers never sign up by hand. An account needs automatic provisioning and single sign-on.
675
+ const must = (field, message) => errors.push(issue(field, message));
676
+ if (!account.provision)
677
+ must('account.provision', 'Choose how customers get their account at your service: from the sign-in (OAuth id_token) or by usebecky calling your provision URL.');
678
+ else if (account.provision === 'oauth' && d.connect && d.connect.mode !== 'oauth')
679
+ must('account.provision', 'Accounts from the sign-in (id_token) need connect mode "oauth". With settings fields, use a provision URL ("provision": "url").');
680
+ else if (account.provision === 'url' && d.connect?.mode === 'oauth')
681
+ must('account.provision', 'With connect mode "oauth", create accounts from the sign-in: "provision": "oauth" (the id_token has the name and email).');
682
+ if (account.provision === 'url' && !account.provision_url)
683
+ must('account.provision_url', "Add your provision URL: usebecky calls it to create the customer's account when they install.");
684
+ if (!account.sso_url)
685
+ must('account.sso_url', 'Add your single sign-on URL: customers open your service from usebecky without a password.');
686
+ }
687
+ const ui = draft.ui;
688
+ if (ui && uiBeingFilled(ui) && !failed.has('ui')) {
689
+ if (blank(ui.url))
690
+ errors.push(issue('ui.url', 'Add your UI address: usebecky asks it for your pages whenever someone opens one.'));
691
+ if (!(Array.isArray(ui.pages) && ui.pages.length) && ui.settings !== true)
692
+ errors.push(issue('ui.pages', UI_NEEDS_A_PAGE));
693
+ }
694
+ // ---- Warnings: usebecky accepts these, but they need a look before you submit -----------------------
695
+ const placeholder = (path, v) => {
696
+ if (typeof v !== 'string')
697
+ return;
698
+ const u = parseUrl(v.trim());
699
+ if (!u)
700
+ return;
701
+ if (/(^|\.)example\.(com|org|net)$/i.test(u.hostname))
702
+ warn(path, `This still points at ${u.hostname}. Put in your real address before you submit.`);
703
+ else if (u.protocol === 'mailto:' && /@example\.(com|org|net)$/i.test(safeDecode(u.pathname)))
704
+ warn(path, 'This is still a placeholder email address.');
705
+ else if (u.protocol === 'http:' && isLoopback(u.hostname))
706
+ warn(path, 'This is a localhost address: fine for the dev server and a local usebecky. Customers need your https address before you submit.');
707
+ };
708
+ if (isObj(m.publisher)) {
709
+ placeholder('publisher.website', m.publisher.website);
710
+ if (typeof m.publisher.email === 'string' && /@example\.(com|org|net)$/i.test(m.publisher.email.trim()))
711
+ warn('publisher.email', 'The publisher email is still a placeholder. usebecky writes to it about reviews and payouts.');
712
+ }
713
+ if (isObj(m.links))
714
+ for (const k of LINK_KEYS)
715
+ placeholder(`links.${k}`, m.links[k]);
716
+ if (isObj(m.connect) && m.connect.mode === 'oauth') {
717
+ placeholder('connect.install_url', m.connect.install_url);
718
+ if (Array.isArray(m.connect.redirect_uris))
719
+ m.connect.redirect_uris.forEach((r, i) => placeholder(`connect.redirect_uris.${i}`, r));
720
+ if (blank(m.webhook_url))
721
+ warn('webhook_url', 'There is no webhook_url, so you will not hear about uninstalls and could keep data you should delete.');
722
+ }
723
+ placeholder('webhook_url', m.webhook_url);
724
+ if (isObj(m.account)) {
725
+ placeholder('account.provision_url', m.account.provision_url);
726
+ placeholder('account.sso_url', m.account.sso_url);
727
+ }
728
+ if (isObj(m.ui))
729
+ placeholder('ui.url', m.ui.url);
730
+ if (typeof m.description === 'string' && m.description.trim() && m.description.trim().length < 80)
731
+ warn('description', 'The description is very short. Say what the extension does, who it is for and what it needs.');
732
+ if (Array.isArray(m.scopes)) {
733
+ const scopes = m.scopes;
734
+ scopes.forEach((s, i) => {
735
+ if (scopes.indexOf(s) !== i)
736
+ warn(`scopes.${i}`, `"${String(s)}" is listed twice.`);
737
+ });
738
+ }
739
+ if (m.capabilities !== undefined)
740
+ warn('capabilities', 'capabilities are set by usebecky only. The import ignores them.');
741
+ // The logo is uploaded in the Developer area (Store listing): the import never reads it from the file.
742
+ const logo = m.logo_url;
743
+ if (blank(logo))
744
+ warn('logo_url', 'No logo named. Upload it in the Developer area under Store listing (PNG, SVG or JPEG, at most 200 KB), and name the file here, like "logo.svg".');
745
+ else if (typeof logo !== 'string')
746
+ warn('logo_url', 'logo_url names the logo file next to usebecky-extension.json, like "logo.svg".');
747
+ else {
748
+ const u = parseUrl(logo);
749
+ if (u) {
750
+ if (!/^https?:$/.test(u.protocol) || !LOGO_TYPES.test(u.pathname))
751
+ warn('logo_url', 'The logo should be a PNG, SVG or JPEG file.');
752
+ }
753
+ else if (!LOGO_TYPES.test(logo))
754
+ warn('logo_url', `The logo must be a PNG, SVG or JPEG file, got "${logo}". The upload refuses anything else.`);
755
+ else if (logo.startsWith('/') || logo.split(/[\\/]/).includes('..'))
756
+ warn('logo_url', 'Name the logo as a file inside your extension folder, like "logo.svg".');
757
+ else if (options.fileInfo) {
758
+ const info = options.fileInfo(logo);
759
+ if (!info)
760
+ warn('logo_url', `The logo file "${logo}" doesn't exist next to usebecky-extension.json.`);
761
+ else if (info.size > MAX_LOGO_BYTES)
762
+ warn('logo_url', `The logo is ${Math.ceil(info.size / 1024)} KB; the upload takes at most 200 KB. Export it smaller (an SVG is usually tiny).`);
763
+ }
764
+ }
765
+ const ok = errors.length === 0;
766
+ return { ok, errors, warnings, manifest: ok ? m : null };
767
+ }
768
+ /** JSON.parse with the line and column of a syntax error, in plain words. */
769
+ export function parseManifestJson(text) {
770
+ try {
771
+ return { value: JSON.parse(text.replace(/^\uFEFF/, '')), error: null };
772
+ }
773
+ catch (e) {
774
+ const msg = e.message;
775
+ const pos = /position (\d+)/.exec(msg)?.[1];
776
+ let where = '';
777
+ if (pos !== undefined) {
778
+ const before = text.slice(0, Number(pos));
779
+ const line = before.split('\n').length;
780
+ const col = Number(pos) - before.lastIndexOf('\n');
781
+ where = ` (line ${line}, column ${col})`;
782
+ }
783
+ return { value: null, error: `This is not valid JSON${where}: ${msg.replace(/ in JSON at position \d+.*$/, '').replace(/\s*\(line \d+ column \d+\)$/, '')}. Look for a missing comma or quote, or a comma after the last item.` };
784
+ }
785
+ }