@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.
- package/README.md +223 -2
- package/dist/accounts.d.ts +85 -0
- package/dist/accounts.js +149 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/run.d.ts +25 -0
- package/dist/cli/run.js +330 -0
- package/dist/cli/skill.d.ts +16 -0
- package/dist/cli/skill.js +106 -0
- package/dist/crypto.d.ts +12 -0
- package/dist/crypto.js +56 -0
- package/dist/dev/pages.d.ts +155 -0
- package/dist/dev/pages.js +243 -0
- package/dist/dev/plans.d.ts +45 -0
- package/dist/dev/plans.js +135 -0
- package/dist/dev/samples.d.ts +61 -0
- package/dist/dev/samples.js +191 -0
- package/dist/dev/server.d.ts +120 -0
- package/dist/dev/server.js +1657 -0
- package/dist/dev/tagging.d.ts +16 -0
- package/dist/dev/tagging.js +81 -0
- package/dist/dev/ui-render.d.ts +25 -0
- package/dist/dev/ui-render.js +256 -0
- package/dist/dev/wordmark.d.ts +1 -0
- package/dist/dev/wordmark.js +2 -0
- package/dist/errors.d.ts +98 -0
- package/dist/errors.js +110 -0
- package/dist/events.d.ts +92 -0
- package/dist/events.js +54 -0
- package/dist/extension.d.ts +214 -0
- package/dist/extension.js +497 -0
- package/dist/handlers.d.ts +39 -0
- package/dist/handlers.js +113 -0
- package/dist/identity.d.ts +99 -0
- package/dist/identity.js +134 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +17 -0
- package/dist/jwt.d.ts +62 -0
- package/dist/jwt.js +152 -0
- package/dist/manifest.d.ts +42 -0
- package/dist/manifest.js +785 -0
- package/dist/node.d.ts +10 -0
- package/dist/node.js +56 -0
- package/dist/pkce.d.ts +9 -0
- package/dist/pkce.js +16 -0
- package/dist/stores.d.ts +100 -0
- package/dist/stores.js +159 -0
- package/dist/types.d.ts +346 -0
- package/dist/types.js +70 -0
- package/dist/ui/handler.d.ts +66 -0
- package/dist/ui/handler.js +105 -0
- package/dist/ui/schema.d.ts +423 -0
- package/dist/ui/schema.js +666 -0
- package/dist/webhooks.d.ts +26 -0
- package/dist/webhooks.js +99 -0
- package/package.json +57 -4
- package/skill/usebecky-extension/SKILL.md +181 -0
- package/skill/usebecky-extension/references/accounts.md +125 -0
- package/skill/usebecky-extension/references/dev-server.md +102 -0
- package/skill/usebecky-extension/references/manifest.md +104 -0
- package/skill/usebecky-extension/references/oauth-and-tokens.md +179 -0
- package/skill/usebecky-extension/references/partner-api.md +87 -0
- package/skill/usebecky-extension/references/submit-and-pricing.md +31 -0
- package/skill/usebecky-extension/references/ui.md +172 -0
- package/skill/usebecky-extension/references/webhooks.md +97 -0
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import type { ExtensionField, ExtensionSettings } from '../types.ts';
|
|
2
|
+
import { type DevPlanOption } from './plans.ts';
|
|
3
|
+
import type { Plan } from '../ui/schema.ts';
|
|
4
|
+
export interface PageProject {
|
|
5
|
+
ref: string;
|
|
6
|
+
name: string;
|
|
7
|
+
plan: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* View.refresh_seconds, by the dashboard's rules: every N seconds, while the tab is visible, no form in the view has
|
|
11
|
+
* unsaved input and no dialog is open, the page is asked for again and the view's element (ui-render.ts wrap) is swapped
|
|
12
|
+
* for the new one; it stops after 30 minutes, or when the new view has no refresh_seconds.
|
|
13
|
+
*/
|
|
14
|
+
export declare const REFRESH_SCRIPT = "<script>(function(){var started=Date.now(),dirty=false,STOP=1800000;\nfunction mark(e){var t=e.target;if(t&&t.closest&&t.closest('[data-ub-refresh] form'))dirty=true}\ndocument.addEventListener('input',mark,true);document.addEventListener('change',mark,true);document.addEventListener('submit',function(){dirty=false},true);\nfunction next(){var el=document.querySelector('[data-ub-refresh]');if(!el)return;var id=el.id;setTimeout(function(){tick(id)},Number(el.getAttribute('data-ub-refresh'))*1000)}\nfunction tick(id){if(Date.now()-started>=STOP)return;if(document.visibilityState!=='visible'||dirty||document.querySelector('dialog[open]'))return next();\nfetch(location.href,{headers:{'x-usebecky-refresh':'1'}}).then(function(r){return r.text()}).then(function(text){var fresh=new DOMParser().parseFromString(text,'text/html').getElementById(id);var el=document.getElementById(id);if(fresh&&el&&!dirty)el.replaceWith(fresh);next()},next)}\nnext()})()</script>";
|
|
15
|
+
export declare function page(title: string, body: string): string;
|
|
16
|
+
export interface NavLink {
|
|
17
|
+
href: string;
|
|
18
|
+
label: string;
|
|
19
|
+
current?: boolean;
|
|
20
|
+
logoUrl?: string | null;
|
|
21
|
+
}
|
|
22
|
+
/** A project page with the sidebar: the extension's pages (listing ui.pages) in their groups, like the dashboard. */
|
|
23
|
+
export declare function projectPage(title: string, project: PageProject, groups: Array<{
|
|
24
|
+
label: string;
|
|
25
|
+
links: NavLink[];
|
|
26
|
+
}>, body: string): string;
|
|
27
|
+
export interface ConsentPageInput {
|
|
28
|
+
extensionName: string;
|
|
29
|
+
publisher: string;
|
|
30
|
+
logoUrl: string | null;
|
|
31
|
+
/** The scopes asked for, in the consent screen's words. */
|
|
32
|
+
scopes: Array<{
|
|
33
|
+
label: string;
|
|
34
|
+
description: string;
|
|
35
|
+
}>;
|
|
36
|
+
dataShared: string[];
|
|
37
|
+
/** The listing's events, when events:read is asked for. */
|
|
38
|
+
events: string[];
|
|
39
|
+
projects: Array<PageProject & {
|
|
40
|
+
installed: boolean;
|
|
41
|
+
connected: boolean;
|
|
42
|
+
}>;
|
|
43
|
+
/** Preselected (the `project` parameter, or the only project). */
|
|
44
|
+
selected: string | null;
|
|
45
|
+
/** The parameters of the consent link, posted back as they came. */
|
|
46
|
+
params: Record<string, string>;
|
|
47
|
+
/** The listing creates the account at the developer's service (and opens it without a password). */
|
|
48
|
+
account?: {
|
|
49
|
+
name: string;
|
|
50
|
+
email: string;
|
|
51
|
+
sso: boolean;
|
|
52
|
+
} | null;
|
|
53
|
+
}
|
|
54
|
+
export declare function consentPage(i: ConsentPageInput): string;
|
|
55
|
+
/** What the consent screen shows for a link it refuses (nothing is redirected). */
|
|
56
|
+
export declare function consentProblemPage(message: string, hint: string | undefined, code: string): string;
|
|
57
|
+
export declare function errorHtml(title: string, message: string): string;
|
|
58
|
+
export interface HomeProject extends PageProject {
|
|
59
|
+
/** null: not added. */
|
|
60
|
+
install: null | {
|
|
61
|
+
status: 'active' | 'error';
|
|
62
|
+
connected: boolean;
|
|
63
|
+
plan?: Plan | null;
|
|
64
|
+
};
|
|
65
|
+
/** Where Install goes: install_url (oauth) or the settings form (fields); null when it can't. */
|
|
66
|
+
installHref: string | null;
|
|
67
|
+
pageHref: string;
|
|
68
|
+
/** "Open in <name>" (single sign-on): /dev/launch, when the listing has account.sso_url and the account exists. */
|
|
69
|
+
openHref?: string | null;
|
|
70
|
+
/** Its pages inside usebecky (listing ui.pages), once installed. */
|
|
71
|
+
pages?: NavLink[];
|
|
72
|
+
}
|
|
73
|
+
export interface HomeInput {
|
|
74
|
+
extensionName: string;
|
|
75
|
+
summary: string;
|
|
76
|
+
logoUrl: string | null;
|
|
77
|
+
mode: 'oauth' | 'fields';
|
|
78
|
+
projects: HomeProject[];
|
|
79
|
+
eventTypes: string[];
|
|
80
|
+
webhookUrl: string | null;
|
|
81
|
+
credentials: {
|
|
82
|
+
clientId: string;
|
|
83
|
+
clientSecret: string;
|
|
84
|
+
webhookSecret: string;
|
|
85
|
+
};
|
|
86
|
+
url: string;
|
|
87
|
+
notice: {
|
|
88
|
+
text: string;
|
|
89
|
+
bad: boolean;
|
|
90
|
+
} | null;
|
|
91
|
+
problems: string[];
|
|
92
|
+
/** The projects act as test projects (`test: true` on the installation and on every event). */
|
|
93
|
+
testProject: boolean;
|
|
94
|
+
/** The listing's plans (pricing "plans", or the one plan "monthly"); empty for a free extension. */
|
|
95
|
+
plans?: DevPlanOption[];
|
|
96
|
+
}
|
|
97
|
+
export declare const usd: (cents: number) => string;
|
|
98
|
+
/** "Pro · $29.00 a month · Trial until 3 Dec", and what comes next. */
|
|
99
|
+
export declare function planLine(p: Plan): string;
|
|
100
|
+
export declare function homePage(i: HomeInput): string;
|
|
101
|
+
export interface SettingsPageInput {
|
|
102
|
+
extensionName: string;
|
|
103
|
+
logoUrl: string | null;
|
|
104
|
+
project: PageProject;
|
|
105
|
+
fields: ExtensionField[];
|
|
106
|
+
/** Current values (secrets never come back). */
|
|
107
|
+
values: Record<string, string | boolean>;
|
|
108
|
+
/** Secret fields that have a saved value: leave them blank to keep it. */
|
|
109
|
+
secretsSet: string[];
|
|
110
|
+
/** Already added: this changes the settings. */
|
|
111
|
+
installed: boolean;
|
|
112
|
+
error: {
|
|
113
|
+
field: string;
|
|
114
|
+
message: string;
|
|
115
|
+
hint?: string;
|
|
116
|
+
} | null;
|
|
117
|
+
/** The values came from the developer's provision endpoint (account.provision "url"): the customer confirms them. */
|
|
118
|
+
filledBy?: string | null;
|
|
119
|
+
}
|
|
120
|
+
/** The first step of installing an extension that creates the account (account.provision "url"). */
|
|
121
|
+
export declare function provisionPage(i: {
|
|
122
|
+
extensionName: string;
|
|
123
|
+
logoUrl: string | null;
|
|
124
|
+
project: PageProject;
|
|
125
|
+
person: {
|
|
126
|
+
name: string;
|
|
127
|
+
email: string;
|
|
128
|
+
};
|
|
129
|
+
error: string | null;
|
|
130
|
+
}): string;
|
|
131
|
+
/** The form a customer fills in to add a fields extension (the dashboard's Install dialog). */
|
|
132
|
+
export declare function settingsPage(i: SettingsPageInput): string;
|
|
133
|
+
export interface ExtensionPageInput {
|
|
134
|
+
extensionName: string;
|
|
135
|
+
logoUrl: string | null;
|
|
136
|
+
project: PageProject;
|
|
137
|
+
mode: 'oauth' | 'fields';
|
|
138
|
+
state: 'not_added' | 'connected' | 'not_connected' | 'reconnect';
|
|
139
|
+
/** Non-secret settings (fields mode). */
|
|
140
|
+
settings: ExtensionSettings;
|
|
141
|
+
fields: ExtensionField[];
|
|
142
|
+
/** Install / Connect again (oauth: install_url; fields: the settings form). */
|
|
143
|
+
actionHref: string | null;
|
|
144
|
+
notice: string | null;
|
|
145
|
+
/** Its pages inside usebecky (listing ui.pages), once installed. */
|
|
146
|
+
pages?: NavLink[];
|
|
147
|
+
/** Its settings view (listing ui.settings), drawn from its blocks, or why it couldn't be. */
|
|
148
|
+
uiSettings?: string | null;
|
|
149
|
+
/** Paid: the listing's plans, the install's plan, the one a plan button or ?plan= picked. */
|
|
150
|
+
plans?: DevPlanOption[];
|
|
151
|
+
plan?: Plan | null;
|
|
152
|
+
pickedPlan?: string | null;
|
|
153
|
+
}
|
|
154
|
+
/** The extension's page in a project: where install_url's return_url sends the customer back to. */
|
|
155
|
+
export declare function extensionPage(i: ExtensionPageInput): string;
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// The dev server's pages, in the words of usebecky's dashboard: the projects with Install (the store), the consent
|
|
2
|
+
// screen ("Connect … to usebecky", Which project?, Cancel / Allow), the settings form of a fields extension and the
|
|
3
|
+
// extension's page in a project (where install_url's return_url points), with its plan and the plan dialog. The home
|
|
4
|
+
// page's dev panel sets an install's plan, status, trial and discount. usebecky's look: aubergine bar with the
|
|
5
|
+
// wordmark, orange buttons with aubergine text, square controls, light and dark, fine at 390 px.
|
|
6
|
+
import { escapeHtml as h } from "../handlers.js";
|
|
7
|
+
import { PLAN_STATUSES_DEV } from "./plans.js";
|
|
8
|
+
import { WORDMARK_SVG } from "./wordmark.js";
|
|
9
|
+
import { UI_CSS } from "./ui-render.js";
|
|
10
|
+
const CSS = `
|
|
11
|
+
:root{--paper:#f6f7fa;--surface:#fff;--sunken:#eef0f5;--ink:#141b33;--ink-2:#333c55;--muted:#4f5970;--line:#e0e4ec;--line-strong:#cbd2de;--accent:#b8420f;--accent-soft:#fff1e9;--mint:#0a7652;--mint-soft:#e5f6ef;--danger:#c22c2c;--danger-soft:#fdecec;--fill:#ff6a2c;--fill-hover:#ff8450;--aubergine:#2c001e;color-scheme:light}
|
|
12
|
+
@media (prefers-color-scheme:dark){:root{--paper:#0e121b;--surface:#151b28;--sunken:#111621;--ink:#eceef5;--ink-2:#c9cfdc;--muted:#a6aec0;--line:#232b3b;--line-strong:#333d52;--accent:#ff6a2c;--accent-soft:#2b1810;--mint:#3fcfa4;--mint-soft:#10302a;--danger:#ff8080;--danger-soft:#3a1a1f;color-scheme:dark}}
|
|
13
|
+
*{box-sizing:border-box}html{-webkit-text-size-adjust:100%}
|
|
14
|
+
body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.55 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
|
|
15
|
+
.bar{background:var(--aubergine);color:#fff;height:72px;display:flex;align-items:center;gap:16px;padding:0 20px}
|
|
16
|
+
.bar svg{display:block;height:36px;width:auto}.tag{color:#ff6a2c;font-size:13px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;padding-top:6px}
|
|
17
|
+
main{max-width:640px;margin:0 auto;padding:32px 20px 64px}
|
|
18
|
+
h1{font-size:26px;line-height:1.25;margin:0 0 6px;letter-spacing:-.01em}h2{font-size:17px;margin:28px 0 10px;font-weight:700}
|
|
19
|
+
p{margin:0 0 12px;color:var(--ink-2)}a{color:var(--accent)}code{font:13.5px ui-monospace,SFMono-Regular,Menlo,monospace;background:var(--sunken);padding:1px 5px;border-radius:4px}
|
|
20
|
+
.head{display:flex;gap:14px;align-items:center;margin-bottom:18px}.logo{width:52px;height:52px;border-radius:6px;border:1px solid var(--line);background:var(--surface);object-fit:contain;flex:none}
|
|
21
|
+
.muted{color:var(--muted)}.small{font-size:14px}
|
|
22
|
+
.strip{display:block;background:var(--surface);border:1px solid var(--line);border-top:none;padding:14px 16px}.strip:first-child{border-top:1px solid var(--line);border-radius:6px 6px 0 0}.strip:last-child{border-radius:0 0 6px 6px}.strip:only-child{border-radius:6px}
|
|
23
|
+
label.strip{display:flex;gap:12px;align-items:center;cursor:pointer}label.strip:has(input:checked){background:var(--accent-soft)}input[type=radio],input[type=checkbox]{accent-color:var(--accent);width:18px;height:18px;margin:0;flex:none}
|
|
24
|
+
ul.list{list-style:none;margin:0;padding:0;border-top:1px solid var(--line)}ul.list li{padding:10px 0 10px 24px;border-bottom:1px solid var(--line);position:relative}ul.list li::before{content:"";position:absolute;left:4px;top:1.05em;width:8px;height:8px;background:var(--accent);border-radius:1px}
|
|
25
|
+
ul.list strong{display:block}ul.list span{display:block;font-size:14.5px;color:var(--muted)}
|
|
26
|
+
.actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:26px;align-items:center}
|
|
27
|
+
button,.button{font:inherit;font-weight:600;font-size:15.5px;border-radius:6px;padding:10px 18px;border:1px solid var(--line-strong);background:var(--surface);color:var(--ink);cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;justify-content:center}
|
|
28
|
+
.primary{background:var(--fill);border-color:var(--fill);color:var(--aubergine)}.primary:hover{background:var(--fill-hover)}
|
|
29
|
+
.danger{color:var(--danger)}button:focus-visible,.button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
30
|
+
.note{background:var(--mint-soft);color:var(--ink);padding:12px 16px;border-radius:6px;margin:0 0 20px}.note.bad{background:var(--danger-soft)}
|
|
31
|
+
.badge{display:inline-block;font-size:12.5px;font-weight:700;padding:1px 7px;border-radius:4px;background:var(--sunken);color:var(--ink-2);margin-left:6px;vertical-align:1px}.badge.ok{background:var(--mint-soft);color:var(--mint)}.badge.bad{background:var(--danger-soft);color:var(--danger)}
|
|
32
|
+
.row{display:flex;flex-wrap:wrap;gap:10px;align-items:center;justify-content:space-between}form.inline{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:12px 0 0}
|
|
33
|
+
.link{background:none;border:none;padding:6px 0;font-size:15px}.link:hover{text-decoration:underline}
|
|
34
|
+
select,input[type=text],input[type=url],input[type=password]{font:inherit;font-size:15px;padding:9px 10px;border-radius:6px;border:1px solid var(--line-strong);background:var(--surface);color:var(--ink);max-width:100%}
|
|
35
|
+
input[type=text],input[type=url],input[type=password]{width:100%}
|
|
36
|
+
.field{margin:0 0 18px}.field>label{display:block;font-weight:600;margin-bottom:6px}.field .help{font-size:14px;color:var(--muted);margin:6px 0 0}.check{display:flex;gap:10px;align-items:flex-start;font-weight:600;cursor:pointer}.check input{margin-top:3px}
|
|
37
|
+
details{margin-top:28px}summary{cursor:pointer;color:var(--muted);font-weight:600}pre{background:var(--sunken);padding:12px 14px;border-radius:6px;overflow:auto;font:13.5px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace}
|
|
38
|
+
.foot{margin-top:36px;font-size:14px;color:var(--muted)}
|
|
39
|
+
.dev-plan{margin-top:12px}.dev-plan summary{font-weight:500;color:var(--ink-2)}.dev-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:10px 14px;margin-top:12px;align-items:end}
|
|
40
|
+
.dev-grid label{display:flex;flex-direction:column;gap:4px;font-size:14px;font-weight:600}.dev-grid label.check{flex-direction:row;align-items:center;gap:8px}.dev-grid input[type=number],.dev-grid input[type=text],.dev-grid select{width:100%;font:inherit;font-size:15px;padding:8px 9px;border-radius:6px;border:1px solid var(--line-strong);background:var(--surface);color:var(--ink)}
|
|
41
|
+
`;
|
|
42
|
+
const head = (title) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>${h(title)} · usebecky dev server</title><style>${CSS}${UI_CSS}</style></head>
|
|
43
|
+
<body><header class="bar"><a href="/" aria-label="usebecky dev server home" style="display:flex">${WORDMARK_SVG}</a><span class="tag">Dev server</span></header>`;
|
|
44
|
+
/**
|
|
45
|
+
* View.refresh_seconds, by the dashboard's rules: every N seconds, while the tab is visible, no form in the view has
|
|
46
|
+
* unsaved input and no dialog is open, the page is asked for again and the view's element (ui-render.ts wrap) is swapped
|
|
47
|
+
* for the new one; it stops after 30 minutes, or when the new view has no refresh_seconds.
|
|
48
|
+
*/
|
|
49
|
+
export const REFRESH_SCRIPT = `<script>(function(){var started=Date.now(),dirty=false,STOP=1800000;
|
|
50
|
+
function mark(e){var t=e.target;if(t&&t.closest&&t.closest('[data-ub-refresh] form'))dirty=true}
|
|
51
|
+
document.addEventListener('input',mark,true);document.addEventListener('change',mark,true);document.addEventListener('submit',function(){dirty=false},true);
|
|
52
|
+
function next(){var el=document.querySelector('[data-ub-refresh]');if(!el)return;var id=el.id;setTimeout(function(){tick(id)},Number(el.getAttribute('data-ub-refresh'))*1000)}
|
|
53
|
+
function tick(id){if(Date.now()-started>=STOP)return;if(document.visibilityState!=='visible'||dirty||document.querySelector('dialog[open]'))return next();
|
|
54
|
+
fetch(location.href,{headers:{'x-usebecky-refresh':'1'}}).then(function(r){return r.text()}).then(function(text){var fresh=new DOMParser().parseFromString(text,'text/html').getElementById(id);var el=document.getElementById(id);if(fresh&&el&&!dirty)el.replaceWith(fresh);next()},next)}
|
|
55
|
+
next()})()</script>`;
|
|
56
|
+
/** The refresh script, when the body has a view that refreshes itself. */
|
|
57
|
+
const refresher = (body) => (body.includes('data-ub-refresh=') ? REFRESH_SCRIPT : '');
|
|
58
|
+
export function page(title, body) {
|
|
59
|
+
return `${head(title)}<main>${body}</main>${refresher(body)}</body></html>`;
|
|
60
|
+
}
|
|
61
|
+
/** A project page with the sidebar: the extension's pages (listing ui.pages) in their groups, like the dashboard. */
|
|
62
|
+
export function projectPage(title, project, groups, body) {
|
|
63
|
+
const nav = groups
|
|
64
|
+
.filter((g) => g.links.length)
|
|
65
|
+
.map((g) => `<div class="group">${h(g.label)}</div>${g.links.map((l) => `<a href="${h(l.href)}"${l.current ? ' aria-current="page"' : ''}>${l.logoUrl ? `<img src="${h(l.logoUrl)}" alt="">` : ''}${h(l.label)}</a>`).join('')}`)
|
|
66
|
+
.join('');
|
|
67
|
+
return `${head(title)}<div class="ub-layout"><nav class="ub-nav" aria-label="${h(project.name)}"><a href="/" style="padding-left:0"><strong>${h(project.name)}</strong></a>${nav}</nav><main>${body}</main></div>${refresher(body)}</body></html>`;
|
|
68
|
+
}
|
|
69
|
+
const logoImg = (url) => (url ? `<img class="logo" src="${h(url)}" alt="">` : '');
|
|
70
|
+
export function consentPage(i) {
|
|
71
|
+
const hidden = Object.entries(i.params)
|
|
72
|
+
.map(([k, v]) => `<input type="hidden" name="${h(k)}" value="${h(v)}">`)
|
|
73
|
+
.join('');
|
|
74
|
+
const projects = i.projects
|
|
75
|
+
.map((p) => `<label class="strip"><input type="radio" name="project" value="${h(p.ref)}" required${p.ref === i.selected ? ' checked' : ''}><span><strong>${h(p.name)}</strong> <span class="muted small">${h(p.ref)}</span>${p.connected ? '<span class="badge ok">Connected</span>' : p.installed ? '<span class="badge">Added</span>' : ''}</span></label>`)
|
|
76
|
+
.join('');
|
|
77
|
+
const can = i.scopes.length ? `<ul class="list">${i.scopes.map((s) => `<li><strong>${h(s.label)}</strong><span>${h(s.description)}</span></li>`).join('')}</ul>` : '<p class="muted">Nothing: it doesn’t need access to your project.</p>';
|
|
78
|
+
const events = i.events.length ? `<p class="muted small" style="margin-top:10px">Events it gets: ${i.events.map((e) => `<code>${h(e)}</code>`).join(' ')}</p>` : '';
|
|
79
|
+
const data = i.dataShared.length ? `<ul class="list">${i.dataShared.map((d) => `<li>${h(d)}</li>`).join('')}</ul>` : '<p class="muted">No data from your project.</p>';
|
|
80
|
+
const by = i.publisher === i.extensionName ? h(i.publisher) : `${h(i.extensionName)} by ${h(i.publisher)}`;
|
|
81
|
+
const account = i.account
|
|
82
|
+
? `<h2>Your account at ${h(i.extensionName)}</h2><ul class="list"><li><strong>${h(i.extensionName)} creates your account with your name and email, no password needed</strong><span>${h(i.account.name)} · ${h(i.account.email)}</span></li>${i.account.sso ? `<li><strong>You can open ${h(i.extensionName)} from usebecky without signing in</strong><span>“Open in ${h(i.extensionName)}” on the extension’s page.</span></li>` : ''}</ul>`
|
|
83
|
+
: '';
|
|
84
|
+
return page(`Connect ${i.extensionName} to usebecky`, `<div class="head">${logoImg(i.logoUrl)}<div><h1>Connect ${h(i.extensionName)} to usebecky</h1><p class="muted" style="margin:0">${by} wants access to one of your projects.</p></div></div>
|
|
85
|
+
<form method="post" action="/oauth/authorize">${hidden}
|
|
86
|
+
<h2>Which project?</h2><div>${projects}</div>
|
|
87
|
+
<h2>${h(i.extensionName)} will be able to</h2>${can}${events}${account}
|
|
88
|
+
<h2>Data shared with ${h(i.publisher)}</h2>${data}
|
|
89
|
+
<div class="actions"><button type="submit" name="decision" value="deny" formnovalidate>Cancel</button><button class="primary" type="submit" name="decision" value="allow">Allow</button></div>
|
|
90
|
+
<p class="muted small" style="margin-top:14px">You can disconnect it any time in your project under Extensions.</p>
|
|
91
|
+
</form>
|
|
92
|
+
<p class="foot">This is the usebecky dev server on your computer. The projects and data are pretend.</p>`);
|
|
93
|
+
}
|
|
94
|
+
/** What the consent screen shows for a link it refuses (nothing is redirected). */
|
|
95
|
+
export function consentProblemPage(message, hint, code) {
|
|
96
|
+
return page('We can’t connect this app', `<h1>We can’t connect this app</h1><p>${h(message)}</p>${hint ? `<p class="muted">${h(hint)}</p>` : ''}<p class="muted small">Error code: <code>${h(code)}</code></p><p class="foot"><a href="/">Back to the dev server</a></p>`);
|
|
97
|
+
}
|
|
98
|
+
export function errorHtml(title, message) {
|
|
99
|
+
return page(title, `<h1>${h(title)}</h1><p>${h(message)}</p><p class="foot"><a href="/">Back to the dev server</a></p>`);
|
|
100
|
+
}
|
|
101
|
+
const MONEY = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
|
|
102
|
+
export const usd = (cents) => MONEY.format(cents / 100);
|
|
103
|
+
const DAY = new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'short', timeZone: 'UTC' });
|
|
104
|
+
const day = (iso) => (iso ? DAY.format(new Date(iso)) : '');
|
|
105
|
+
/** "Pro · $29.00 a month · Trial until 3 Dec", and what comes next. */
|
|
106
|
+
export function planLine(p) {
|
|
107
|
+
const status = p.status === 'trialing' ? `Free trial until ${day(p.trial_ends_at)}` : p.status === 'past_due' ? 'Payment failed' : p.status === 'canceled' ? 'Canceled' : p.cancel_at_period_end ? `Ends ${day(p.current_period_end)}` : `Renews ${day(p.current_period_end)}`;
|
|
108
|
+
const next = p.next_plan ? ` · ${h(p.next_plan.name)} from ${day(p.next_plan.starts_at)}` : '';
|
|
109
|
+
const discount = p.discount ? ` · ${h(p.discount.code)} (${p.discount.percent_off ? `${p.discount.percent_off}% off` : usd(p.discount.amount_off ?? 0) + ' off'})` : '';
|
|
110
|
+
return `<strong>${h(p.name)}</strong> · ${usd(p.amount)} a month · ${h(status)}${next}${discount}`;
|
|
111
|
+
}
|
|
112
|
+
/** The dev panel: set the install's plan as usebecky would have it (plan, status, trial, next plan, discount). */
|
|
113
|
+
function planPanel(ref, plan, plans) {
|
|
114
|
+
const opt = (v, label, on) => `<option value="${h(v)}"${on ? ' selected' : ''}>${h(label)}</option>`;
|
|
115
|
+
const trialDays = plan.trial_ends_at ? Math.max(1, Math.ceil((Date.parse(plan.trial_ends_at) - Date.now()) / 86_400_000)) : 7;
|
|
116
|
+
const d = plan.discount;
|
|
117
|
+
return `<details class="dev-plan"><summary>Plan: ${planLine(plan)}</summary>
|
|
118
|
+
<form class="dev-grid" method="post" action="/dev/plan"><input type="hidden" name="project" value="${h(ref)}">
|
|
119
|
+
<label>Plan<select name="plan">${plans.map((p) => opt(p.id, `${p.name} (${usd(p.amount)})`, p.id === plan.id)).join('')}</select></label>
|
|
120
|
+
<label>Status<select name="status">${PLAN_STATUSES_DEV.map((s) => opt(s, s, s === plan.status)).join('')}</select></label>
|
|
121
|
+
<label>Trial days left<input type="number" name="trial_days" min="1" max="30" value="${trialDays}"></label>
|
|
122
|
+
<label>Next plan<select name="next_plan">${opt('', 'None', !plan.next_plan)}${plans.filter((p) => p.id !== plan.id).map((p) => opt(p.id, p.name, plan.next_plan?.id === p.id)).join('')}</select></label>
|
|
123
|
+
<label>Discount code<input type="text" name="discount_code" value="${h(d?.code ?? '')}" placeholder="LAUNCH50"></label>
|
|
124
|
+
<label>Percent off<input type="number" name="discount_percent" min="1" max="100" value="${d?.percent_off ?? ''}"></label>
|
|
125
|
+
<label>Or cents off<input type="number" name="discount_amount" min="1" value="${d?.amount_off ?? ''}"></label>
|
|
126
|
+
<label>For<select name="discount_duration">${opt('once', 'Once', d?.duration === 'once')}${opt('repeating', 'Some months', d?.duration === 'repeating')}${opt('forever', 'Forever', d?.duration === 'forever')}</select></label>
|
|
127
|
+
<label>Months<input type="number" name="discount_months" min="1" max="36" value="3"></label>
|
|
128
|
+
<label class="check"><input type="checkbox" name="cancel_at_period_end" value="true"${plan.cancel_at_period_end ? ' checked' : ''}> Ends at period end</label>
|
|
129
|
+
<div class="row" style="grid-column:1/-1;justify-content:flex-start;gap:8px"><button class="primary" type="submit">Apply</button><button type="submit" name="renew" value="1">Start next period</button></div>
|
|
130
|
+
</form><p class="muted small" style="margin:8px 0 0">Your extension gets extension.plan_changed when the plan, status, end, next plan or discount change.</p></details>`;
|
|
131
|
+
}
|
|
132
|
+
/** Install with a plan picked first (paid extensions): GET /dev/start remembers it, then the install starts. */
|
|
133
|
+
function installWithPlan(ref, plans, label = 'Install') {
|
|
134
|
+
return `<form class="inline" method="get" action="/dev/start" style="margin:0"><input type="hidden" name="project" value="${h(ref)}"><select name="plan" aria-label="Plan">${plans.map((p) => `<option value="${h(p.id)}">${h(p.name)} · ${usd(p.amount)}</option>`).join('')}</select><button class="primary" type="submit">${h(label)}</button></form>`;
|
|
135
|
+
}
|
|
136
|
+
export function homePage(i) {
|
|
137
|
+
const notice = i.notice ? `<p class="note${i.notice.bad ? ' bad' : ''}">${h(i.notice.text)}</p>` : '';
|
|
138
|
+
const problems = i.problems.length ? `<p class="note bad">${i.problems.map(h).join('<br>')}</p>` : '';
|
|
139
|
+
const options = i.eventTypes.map((t) => `<option value="${h(t)}">${h(t)}</option>`).join('');
|
|
140
|
+
const rows = i.projects
|
|
141
|
+
.map((p) => {
|
|
142
|
+
const title = `<span><strong>${h(p.name)}</strong> <span class="muted small">${h(p.ref)} · ${h(p.plan)}${i.testProject ? ' · test project' : ''}</span>`;
|
|
143
|
+
if (!p.install) {
|
|
144
|
+
const action = p.installHref
|
|
145
|
+
? i.plans?.length
|
|
146
|
+
? installWithPlan(p.ref, i.plans)
|
|
147
|
+
: `<a class="button primary" href="${h(p.installHref)}">Install</a>`
|
|
148
|
+
: '<span class="muted small">Add <code>connect.install_url</code> to usebecky-extension.json to install it.</span>';
|
|
149
|
+
return `<div class="strip"><div class="row">${title}</span>${action}</div></div>`;
|
|
150
|
+
}
|
|
151
|
+
const badge = p.install.status === 'error' ? '<span class="badge bad">Reconnect</span>' : p.install.connected ? '<span class="badge ok">Connected</span>' : '<span class="badge">Not connected yet</span>';
|
|
152
|
+
const open = p.openHref ? `<a class="button primary" href="${h(p.openHref)}" target="_blank" rel="noopener">Open in ${h(i.extensionName)}</a> ` : '';
|
|
153
|
+
return `<div class="strip"><div class="row">${title}${badge}</span><span>${open}${(p.pages ?? []).map((l) => `<a href="${h(l.href)}">${h(l.label)}</a> · `).join('')}<a href="${h(p.pageHref)}">Extension page</a> · <form method="post" action="/dev/uninstall" style="display:inline;margin:0"><input type="hidden" name="project" value="${h(p.ref)}"><button class="link danger" type="submit">Disconnect</button></form></span></div>
|
|
154
|
+
<form class="inline" method="post" action="/dev/send"><input type="hidden" name="project" value="${h(p.ref)}"><select name="type" aria-label="Event to send">${options}</select><button type="submit">Send event</button></form>${p.install.plan && i.plans?.length ? planPanel(p.ref, p.install.plan, i.plans) : ''}</div>`;
|
|
155
|
+
})
|
|
156
|
+
.join('');
|
|
157
|
+
return page(i.extensionName, `${notice}${problems}<div class="head">${logoImg(i.logoUrl)}<div><h1>${h(i.extensionName)}</h1><p class="muted" style="margin:0">${h(i.summary)}</p></div></div>
|
|
158
|
+
<h2>Your projects</h2><div>${rows}</div>
|
|
159
|
+
<p class="muted small" style="margin-top:14px">${i.mode === 'oauth'
|
|
160
|
+
? 'Install goes through the same steps as for a customer: your install_url (with ?project and ?return_url), the consent screen, your callback.'
|
|
161
|
+
: 'Install opens the settings form a customer fills in; then usebecky sends extension.installed with the settings.'}</p>
|
|
162
|
+
<details><summary>Test credentials and addresses</summary>
|
|
163
|
+
<p class="small" style="margin-top:12px"><code>npm run dev</code> passes these to your extension. To run it some other way, put them in its environment:</p>
|
|
164
|
+
<pre>USEBECKY_API_URL=${h(i.url)}
|
|
165
|
+
USEBECKY_DASHBOARD_URL=${h(i.url)}
|
|
166
|
+
USEBECKY_CLIENT_ID=${h(i.credentials.clientId)}
|
|
167
|
+
USEBECKY_CLIENT_SECRET=${h(i.credentials.clientSecret)}
|
|
168
|
+
USEBECKY_WEBHOOK_SECRET=${h(i.credentials.webhookSecret)}</pre>
|
|
169
|
+
<p class="small">Events go to ${i.webhookUrl ? `<code>${h(i.webhookUrl)}</code>` : 'nowhere yet: add <code>webhook_url</code> to usebecky-extension.json'}.</p>
|
|
170
|
+
<p class="small">${i.testProject
|
|
171
|
+
? 'These are test projects: the installation says <code>"test": true</code>, and so does every event.'
|
|
172
|
+
: 'These act like real projects. To try a test project (<code>"test": true</code> on the installation and on every event), start the dev server with <code>--test-project</code>.'}</p></details>
|
|
173
|
+
<p class="foot">A pretend usebecky on your computer. Restarting it forgets installs: install again.</p>`);
|
|
174
|
+
}
|
|
175
|
+
/** The first step of installing an extension that creates the account (account.provision "url"). */
|
|
176
|
+
export function provisionPage(i) {
|
|
177
|
+
const error = i.error ? `<p class="note bad">We couldn't create your account at ${h(i.extensionName)}: ${h(i.error)}</p>` : '';
|
|
178
|
+
return page(`Install ${i.extensionName}`, `${error}<div class="head">${logoImg(i.logoUrl)}<div><h1>Install: ${h(i.extensionName)}</h1><p class="muted" style="margin:0">In ${h(i.project.name)}</p></div></div>
|
|
179
|
+
<ul class="list"><li><strong>${h(i.extensionName)} creates your account with your name and email, no password needed</strong><span>${h(i.person.name)} · ${h(i.person.email)}</span></li><li><strong>You can open ${h(i.extensionName)} from usebecky without signing in</strong><span>Nothing to sign up for.</span></li></ul>
|
|
180
|
+
<form method="post" action="/dev/provision"><input type="hidden" name="project" value="${h(i.project.ref)}">
|
|
181
|
+
<div class="actions"><button class="primary" type="submit">${i.error ? 'Try again' : `Create my ${h(i.extensionName)} account`}</button><a class="button" href="/">Cancel</a></div></form>
|
|
182
|
+
<p class="foot">The dev server sends a signed request to your <code>account.provision_url</code> (with Idempotency-Key = the install id) and fills the settings form with your answer.</p>`);
|
|
183
|
+
}
|
|
184
|
+
/** The form a customer fills in to add a fields extension (the dashboard's Install dialog). */
|
|
185
|
+
export function settingsPage(i) {
|
|
186
|
+
const fields = i.fields
|
|
187
|
+
.map((f) => {
|
|
188
|
+
const id = `f_${f.key}`;
|
|
189
|
+
const help = f.help ? `<p class="help">${h(f.help)}</p>` : '';
|
|
190
|
+
const bad = i.error?.field === f.key ? ' style="border-color:var(--danger)"' : '';
|
|
191
|
+
if (f.type === 'boolean') {
|
|
192
|
+
return `<div class="field"><label class="check" for="${id}"><input type="checkbox" id="${id}" name="${h(f.key)}" value="true"${i.values[f.key] === true ? ' checked' : ''}${f.required ? ' required' : ''}><span>${h(f.label)}</span></label>${help}</div>`;
|
|
193
|
+
}
|
|
194
|
+
const type = f.type === 'secret' ? 'password' : f.type === 'url' ? 'url' : 'text';
|
|
195
|
+
const kept = f.type === 'secret' && i.secretsSet.includes(f.key);
|
|
196
|
+
const value = f.type === 'secret' ? '' : typeof i.values[f.key] === 'string' ? i.values[f.key] : '';
|
|
197
|
+
const placeholder = kept ? 'Saved. Leave empty to keep it.' : (f.placeholder ?? '');
|
|
198
|
+
return `<div class="field"><label for="${id}">${h(f.label)}${f.required ? '' : ' <span class="muted small">(optional)</span>'}</label><input type="${type}" id="${id}" name="${h(f.key)}" value="${h(value)}"${placeholder ? ` placeholder="${h(placeholder)}"` : ''}${f.required && !kept ? ' required' : ''}${bad} autocomplete="off">${help}</div>`;
|
|
199
|
+
})
|
|
200
|
+
.join('');
|
|
201
|
+
const error = i.error ? `<p class="note bad">${h(i.error.message)}${i.error.hint ? ` ${h(i.error.hint)}` : ''}</p>` : '';
|
|
202
|
+
const filled = i.filledBy ? `<p class="note">Your account at ${h(i.filledBy)} is ready. Filled in by ${h(i.filledBy)}: check and confirm.</p>` : '';
|
|
203
|
+
return page(`${i.installed ? 'Settings' : 'Install'} ${i.extensionName}`, `${error}${filled}<div class="head">${logoImg(i.logoUrl)}<div><h1>${i.installed ? 'Settings' : 'Install'}: ${h(i.extensionName)}</h1><p class="muted" style="margin:0">In ${h(i.project.name)}</p></div></div>
|
|
204
|
+
<form method="post" action="/dev/install"><input type="hidden" name="project" value="${h(i.project.ref)}">${fields}
|
|
205
|
+
<div class="actions"><button class="primary" type="submit">${i.installed ? 'Save' : 'Install'}</button><a class="button" href="/">Cancel</a></div></form>
|
|
206
|
+
<p class="foot">Yes/no fields arrive as true or false; secret fields are never sent to the extension.</p>`);
|
|
207
|
+
}
|
|
208
|
+
/** usebecky's plan dialog, as a section of the extension's page: pick a plan, Change plan (or Install with it). */
|
|
209
|
+
function planSection(i) {
|
|
210
|
+
const plans = i.plans ?? [];
|
|
211
|
+
if (!plans.length || (!i.plan && i.state !== 'not_added'))
|
|
212
|
+
return '';
|
|
213
|
+
if (i.state === 'not_added')
|
|
214
|
+
return `<h2>Plan</h2>${installWithPlan(i.project.ref, plans.filter((p) => p.id === i.pickedPlan).concat(plans.filter((p) => p.id !== i.pickedPlan)))}`;
|
|
215
|
+
const current = i.plan;
|
|
216
|
+
const picked = i.pickedPlan && plans.some((p) => p.id === i.pickedPlan) ? i.pickedPlan : current.id;
|
|
217
|
+
const rows = plans
|
|
218
|
+
.map((p) => `<label class="strip"><input type="radio" name="plan" value="${h(p.id)}"${p.id === picked ? ' checked' : ''}><span><strong>${h(p.name)}</strong> <span class="muted small">${usd(p.amount)} a month</span>${p.id === current.id ? '<span class="badge ok">Current</span>' : ''}${current.next_plan?.id === p.id ? '<span class="badge">Next</span>' : ''}${p.summary ? `<span class="muted small" style="display:block">${h(p.summary)}</span>` : ''}</span></label>`)
|
|
219
|
+
.join('');
|
|
220
|
+
return `<h2 id="plan">Plan</h2><p>${planLine(current)}</p>${plans.length > 1 ? `<form method="post" action="/dev/plan-change" style="margin:0 0 22px"><input type="hidden" name="project" value="${h(i.project.ref)}"><div>${rows}</div>
|
|
221
|
+
<p class="muted small" style="margin:10px 0 0">${current.status === 'trialing' ? 'In the free trial a change takes effect now, at no cost.' : 'An upgrade takes effect now (the difference is charged at once); a downgrade at the end of the period.'}</p>
|
|
222
|
+
<div class="actions" style="margin-top:14px"><button class="primary" type="submit">Change plan</button></div></form>` : ''}`;
|
|
223
|
+
}
|
|
224
|
+
/** The extension's page in a project: where install_url's return_url sends the customer back to. */
|
|
225
|
+
export function extensionPage(i) {
|
|
226
|
+
const status = {
|
|
227
|
+
not_added: 'Not added to this project.',
|
|
228
|
+
connected: 'Connected.',
|
|
229
|
+
not_connected: i.mode === 'oauth' ? 'Added, but not connected yet: finish on the developer’s website.' : 'Added. Fill in the required settings.',
|
|
230
|
+
reconnect: 'Its access was revoked. Connect it again.',
|
|
231
|
+
}[i.state];
|
|
232
|
+
const shown = i.fields.filter((f) => f.type !== 'secret' && i.settings[f.key] !== undefined);
|
|
233
|
+
const settings = i.mode === 'fields' && i.state !== 'not_added' && shown.length
|
|
234
|
+
? `<h2>Settings</h2><ul class="list">${shown.map((f) => `<li><strong>${h(f.label)}</strong><span>${typeof i.settings[f.key] === 'boolean' ? (i.settings[f.key] ? 'Yes' : 'No') : h(String(i.settings[f.key]))}</span></li>`).join('')}</ul>`
|
|
235
|
+
: '';
|
|
236
|
+
const label = i.state === 'not_added' ? 'Install' : i.mode === 'fields' ? 'Change settings' : i.state === 'connected' ? 'Open on the developer’s website' : 'Connect';
|
|
237
|
+
const action = i.actionHref ? `<a class="button${i.state === 'connected' ? '' : ' primary'}" href="${h(i.actionHref)}">${label}</a>` : '';
|
|
238
|
+
const disconnect = i.state === 'not_added' ? '' : `<form method="post" action="/dev/uninstall" style="margin:0"><input type="hidden" name="project" value="${h(i.project.ref)}"><button class="danger" type="submit">Disconnect</button></form>`;
|
|
239
|
+
return page(`${i.extensionName} · ${i.project.name}`, `${i.notice ? `<p class="note">${h(i.notice)}</p>` : ''}<div class="head">${logoImg(i.logoUrl)}<div><h1>${h(i.extensionName)}</h1><p class="muted" style="margin:0">${h(i.project.name)} · Extensions</p></div></div>
|
|
240
|
+
<p>${h(status)}</p>${planSection(i)}${settings}${i.pages?.length ? `<p>Its pages: ${i.pages.map((l) => `<a href="${h(l.href)}">${h(l.label)}</a>`).join(' · ')}</p>` : ''}${i.uiSettings ? `<h2>Settings view</h2>${i.uiSettings}` : ''}
|
|
241
|
+
<div class="actions">${action}${disconnect}</div>
|
|
242
|
+
<p class="foot">The extension’s page in the project, as usebecky’s dashboard shows it (install_url’s <code>return_url</code> points here). <a href="/">Back to the dev server</a></p>`);
|
|
243
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { PlanDiscount, PlanStatus, Plan } from '../ui/schema.ts';
|
|
2
|
+
export interface DevPlanOption {
|
|
3
|
+
id: string;
|
|
4
|
+
name: string;
|
|
5
|
+
/** US cents a month. */
|
|
6
|
+
amount: number;
|
|
7
|
+
summary?: string;
|
|
8
|
+
}
|
|
9
|
+
export declare const PLAN_STATUSES_DEV: readonly PlanStatus[];
|
|
10
|
+
/** An install's plan on the dev server. */
|
|
11
|
+
export interface DevPlanState {
|
|
12
|
+
id: string;
|
|
13
|
+
status: PlanStatus;
|
|
14
|
+
trialEndsAt: string | null;
|
|
15
|
+
periodEnd: string;
|
|
16
|
+
cancelAtPeriodEnd: boolean;
|
|
17
|
+
nextPlanId: string | null;
|
|
18
|
+
discount: PlanDiscount | null;
|
|
19
|
+
}
|
|
20
|
+
/** A problem with what the dev panel or the plan dialog sent (400 with the field). */
|
|
21
|
+
export declare class DevPlanError extends Error {
|
|
22
|
+
field: string;
|
|
23
|
+
constructor(field: string, message: string);
|
|
24
|
+
}
|
|
25
|
+
/** A new install's plan: the one picked before installing (or the first), in the listing's free trial if it has one. */
|
|
26
|
+
export declare function startPlan(plans: DevPlanOption[], trialDays: number, picked?: string | null): DevPlanState;
|
|
27
|
+
/** The plan object, as usebecky sends it (GET /installation, extension.installed, ui requests, extension.plan_changed). */
|
|
28
|
+
export declare function planView(s: DevPlanState, plans: DevPlanOption[]): Plan;
|
|
29
|
+
/** What extension.plan_changed is about: id, status, cancel_at_period_end, next_plan, the discount's code (like usebecky). */
|
|
30
|
+
export declare function planKey(p: Plan | null): string;
|
|
31
|
+
/** A discount code as usebecky stores it: 3 to 30 letters, digits or dashes, upper case. */
|
|
32
|
+
export declare const DISCOUNT_CODE_RE: RegExp;
|
|
33
|
+
/**
|
|
34
|
+
* The dev panel: plan, status, trial days left, cancel at period end, next plan, discount (code with percent or cents
|
|
35
|
+
* off, once / for some months / forever, like a code made in the Developer area). Fields left out stay as they are; a
|
|
36
|
+
* form sends them all.
|
|
37
|
+
*/
|
|
38
|
+
export declare function applyPanel(s: DevPlanState, plans: DevPlanOption[], f: Record<string, unknown>): DevPlanState;
|
|
39
|
+
/** usebecky's plan dialog: what "Change plan" to `target` does. */
|
|
40
|
+
export declare function changePlan(s: DevPlanState, plans: DevPlanOption[], target: string): {
|
|
41
|
+
state: DevPlanState;
|
|
42
|
+
effect: 'now' | 'period_end' | 'undone' | 'none';
|
|
43
|
+
};
|
|
44
|
+
/** "Start next period": the trial or period ends; a waiting downgrade takes over; a plan set to end is canceled. */
|
|
45
|
+
export declare function renew(s: DevPlanState): DevPlanState;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
export const PLAN_STATUSES_DEV = ['trialing', 'active', 'past_due', 'canceled'];
|
|
2
|
+
const DAY_MS = 86_400_000;
|
|
3
|
+
const inDays = (days, from = Date.now()) => new Date(from + days * DAY_MS).toISOString();
|
|
4
|
+
/** A problem with what the dev panel or the plan dialog sent (400 with the field). */
|
|
5
|
+
export class DevPlanError extends Error {
|
|
6
|
+
field;
|
|
7
|
+
constructor(field, message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.field = field;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** A new install's plan: the one picked before installing (or the first), in the listing's free trial if it has one. */
|
|
13
|
+
export function startPlan(plans, trialDays, picked) {
|
|
14
|
+
const id = plans.find((p) => p.id === picked)?.id ?? plans[0].id;
|
|
15
|
+
const trial = trialDays > 0 ? inDays(trialDays) : null;
|
|
16
|
+
return { id, status: trial ? 'trialing' : 'active', trialEndsAt: trial, periodEnd: trial ?? inDays(30), cancelAtPeriodEnd: false, nextPlanId: null, discount: null };
|
|
17
|
+
}
|
|
18
|
+
/** The plan object, as usebecky sends it (GET /installation, extension.installed, ui requests, extension.plan_changed). */
|
|
19
|
+
export function planView(s, plans) {
|
|
20
|
+
const plan = plans.find((p) => p.id === s.id) ?? plans[0];
|
|
21
|
+
const next = s.nextPlanId ? plans.find((p) => p.id === s.nextPlanId && p.id !== plan.id) : undefined;
|
|
22
|
+
return {
|
|
23
|
+
id: plan.id,
|
|
24
|
+
name: plan.name,
|
|
25
|
+
amount: plan.amount,
|
|
26
|
+
currency: 'usd',
|
|
27
|
+
status: s.status,
|
|
28
|
+
trial_ends_at: s.status === 'trialing' ? s.trialEndsAt : null,
|
|
29
|
+
current_period_end: s.periodEnd,
|
|
30
|
+
cancel_at_period_end: s.cancelAtPeriodEnd,
|
|
31
|
+
next_plan: next ? { id: next.id, name: next.name, amount: next.amount, starts_at: s.periodEnd } : null,
|
|
32
|
+
discount: s.discount ? { ...s.discount } : null,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** What extension.plan_changed is about: id, status, cancel_at_period_end, next_plan, the discount's code (like usebecky). */
|
|
36
|
+
export function planKey(p) {
|
|
37
|
+
if (!p)
|
|
38
|
+
return 'null';
|
|
39
|
+
return JSON.stringify([p.id, p.status, p.cancel_at_period_end, p.next_plan ? [p.next_plan.id, p.next_plan.starts_at] : null, p.discount?.code ?? null]);
|
|
40
|
+
}
|
|
41
|
+
/** A discount code as usebecky stores it: 3 to 30 letters, digits or dashes, upper case. */
|
|
42
|
+
export const DISCOUNT_CODE_RE = /^[A-Z0-9-]{3,30}$/;
|
|
43
|
+
const addMonths = (months) => {
|
|
44
|
+
const d = new Date();
|
|
45
|
+
d.setUTCMonth(d.getUTCMonth() + months);
|
|
46
|
+
return d.toISOString();
|
|
47
|
+
};
|
|
48
|
+
const str = (v) => (typeof v === 'string' ? v.trim() : '');
|
|
49
|
+
/**
|
|
50
|
+
* The dev panel: plan, status, trial days left, cancel at period end, next plan, discount (code with percent or cents
|
|
51
|
+
* off, once / for some months / forever, like a code made in the Developer area). Fields left out stay as they are; a
|
|
52
|
+
* form sends them all.
|
|
53
|
+
*/
|
|
54
|
+
export function applyPanel(s, plans, f) {
|
|
55
|
+
const next = { ...s };
|
|
56
|
+
if (f.plan !== undefined) {
|
|
57
|
+
if (!plans.some((p) => p.id === f.plan))
|
|
58
|
+
throw new DevPlanError('plan', `"plan" must be one of: ${plans.map((p) => p.id).join(', ')}.`);
|
|
59
|
+
next.id = f.plan;
|
|
60
|
+
}
|
|
61
|
+
if (f.status !== undefined) {
|
|
62
|
+
if (!PLAN_STATUSES_DEV.includes(f.status))
|
|
63
|
+
throw new DevPlanError('status', `"status" must be one of: ${PLAN_STATUSES_DEV.join(', ')}.`);
|
|
64
|
+
next.status = f.status;
|
|
65
|
+
}
|
|
66
|
+
if (next.status === 'trialing') {
|
|
67
|
+
const days = f.trial_days === undefined || f.trial_days === '' ? null : Number(f.trial_days);
|
|
68
|
+
if (days !== null && (!Number.isInteger(days) || days < 1 || days > 30))
|
|
69
|
+
throw new DevPlanError('trial_days', 'Trial days must be 1 to 30.');
|
|
70
|
+
if (days !== null)
|
|
71
|
+
next.trialEndsAt = inDays(days);
|
|
72
|
+
else if (!next.trialEndsAt || Date.parse(next.trialEndsAt) <= Date.now())
|
|
73
|
+
next.trialEndsAt = inDays(7);
|
|
74
|
+
next.periodEnd = next.trialEndsAt;
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
next.trialEndsAt = null;
|
|
78
|
+
if (Date.parse(next.periodEnd) <= Date.now())
|
|
79
|
+
next.periodEnd = inDays(30);
|
|
80
|
+
}
|
|
81
|
+
if (f.cancel_at_period_end !== undefined)
|
|
82
|
+
next.cancelAtPeriodEnd = f.cancel_at_period_end === true || f.cancel_at_period_end === 'true' || f.cancel_at_period_end === 'on';
|
|
83
|
+
if (f.next_plan !== undefined) {
|
|
84
|
+
const id = f.next_plan === null ? '' : str(f.next_plan);
|
|
85
|
+
if (id && !plans.some((p) => p.id === id))
|
|
86
|
+
throw new DevPlanError('next_plan', `"next_plan" must be one of: ${plans.map((p) => p.id).join(', ')}, or empty.`);
|
|
87
|
+
next.nextPlanId = id && id !== next.id ? id : null;
|
|
88
|
+
}
|
|
89
|
+
else if (next.nextPlanId === next.id)
|
|
90
|
+
next.nextPlanId = null;
|
|
91
|
+
if (f.discount_code !== undefined) {
|
|
92
|
+
const code = str(f.discount_code).toUpperCase();
|
|
93
|
+
if (!code)
|
|
94
|
+
next.discount = null;
|
|
95
|
+
else {
|
|
96
|
+
if (!DISCOUNT_CODE_RE.test(code))
|
|
97
|
+
throw new DevPlanError('discount_code', 'A code is 3 to 30 letters, digits or dashes, like LAUNCH50.');
|
|
98
|
+
const percent = f.discount_percent === undefined || f.discount_percent === '' ? null : Number(f.discount_percent);
|
|
99
|
+
const amount = f.discount_amount === undefined || f.discount_amount === '' ? null : Number(f.discount_amount);
|
|
100
|
+
if (percent !== null && (!Number.isInteger(percent) || percent < 1 || percent > 100))
|
|
101
|
+
throw new DevPlanError('discount_percent', 'Percent off must be 1 to 100.');
|
|
102
|
+
if (amount !== null && (!Number.isInteger(amount) || amount < 1))
|
|
103
|
+
throw new DevPlanError('discount_amount', 'Cents off must be a whole number, 1 or more.');
|
|
104
|
+
if ((percent === null) === (amount === null))
|
|
105
|
+
throw new DevPlanError('discount_percent', 'Give the discount either a percent or an amount in cents.');
|
|
106
|
+
const duration = f.discount_duration === 'repeating' || f.discount_duration === 'forever' ? f.discount_duration : 'once';
|
|
107
|
+
const months = f.discount_months === undefined || f.discount_months === '' ? 3 : Number(f.discount_months);
|
|
108
|
+
if (duration === 'repeating' && (!Number.isInteger(months) || months < 1 || months > 36))
|
|
109
|
+
throw new DevPlanError('discount_months', 'Months must be 1 to 36.');
|
|
110
|
+
// once: the next payment (after the trial); repeating: when its months are over; forever: no end.
|
|
111
|
+
const endsAt = duration === 'forever' ? null : duration === 'repeating' ? addMonths(months) : next.status === 'trialing' ? next.trialEndsAt : next.periodEnd;
|
|
112
|
+
next.discount = { code, ...(percent !== null ? { percent_off: percent } : { amount_off: amount }), duration, ends_at: endsAt };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return next;
|
|
116
|
+
}
|
|
117
|
+
/** usebecky's plan dialog: what "Change plan" to `target` does. */
|
|
118
|
+
export function changePlan(s, plans, target) {
|
|
119
|
+
const to = plans.find((p) => p.id === target);
|
|
120
|
+
if (!to)
|
|
121
|
+
throw new DevPlanError('plan', `"plan" must be one of: ${plans.map((p) => p.id).join(', ')}.`);
|
|
122
|
+
const from = plans.find((p) => p.id === s.id) ?? plans[0];
|
|
123
|
+
if (to.id === from.id)
|
|
124
|
+
return s.nextPlanId ? { state: { ...s, nextPlanId: null }, effect: 'undone' } : { state: s, effect: 'none' };
|
|
125
|
+
if (s.status === 'trialing' || to.amount >= from.amount)
|
|
126
|
+
return { state: { ...s, id: to.id, nextPlanId: null }, effect: 'now' };
|
|
127
|
+
return { state: { ...s, nextPlanId: to.id }, effect: 'period_end' };
|
|
128
|
+
}
|
|
129
|
+
/** "Start next period": the trial or period ends; a waiting downgrade takes over; a plan set to end is canceled. */
|
|
130
|
+
export function renew(s) {
|
|
131
|
+
if (s.cancelAtPeriodEnd)
|
|
132
|
+
return { ...s, status: 'canceled', trialEndsAt: null };
|
|
133
|
+
const from = Math.max(Date.now(), Date.parse(s.periodEnd) || 0);
|
|
134
|
+
return { ...s, id: s.nextPlanId ?? s.id, nextPlanId: null, status: 'active', trialEndsAt: null, periodEnd: inDays(30, from) };
|
|
135
|
+
}
|