@sqid-dev/playground 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,18 @@
1
+ <section class="wrap">
2
+ <span class="eyebrow">DESKS</span>
3
+ <h1>Three desks. One of them is yours.</h1>
4
+ <div class="products">
5
+ <a href="/desk" class="product" data-sqid-label="view_rise" data-sqid-type="key_event">
6
+ <div class="product-art" aria-hidden="true"><div class="desk small"><span class="leg"></span><span class="leg"></span></div></div>
7
+ <strong>Driftwood Rise</strong><span>Sit-stand, solid top, 48 to 72 in.</span><em>$749</em>
8
+ </a>
9
+ <a href="/desk" class="product" data-sqid-label="view_tide" data-sqid-type="key_event">
10
+ <div class="product-art" aria-hidden="true"><div class="desk small dark"><span class="leg"></span><span class="leg"></span></div></div>
11
+ <strong>Driftwood Tide</strong><span>Dual motor, cable tray, 60 to 84 in.</span><em>$1,149</em>
12
+ </a>
13
+ <a href="/desk" class="product" data-sqid-label="view_shoal" data-sqid-type="key_event">
14
+ <div class="product-art" aria-hidden="true"><div class="desk small light"><span class="leg"></span><span class="leg"></span></div></div>
15
+ <strong>Driftwood Shoal</strong><span>Fixed height, for the quiet corner.</span><em>$429</em>
16
+ </a>
17
+ </div>
18
+ </section>
@@ -0,0 +1,25 @@
1
+ <section class="hero wrap">
2
+ <div class="hero-copy">
3
+ <span class="eyebrow">STANDING DESKS FOR TEAMS</span>
4
+ <h1 id="hero-title" data-default="Desks that make the office worth the commute.">Desks that make the office worth the commute.</h1>
5
+ <p id="hero-sub" data-default="Solid wood tops, quiet motors, a ten-year warranty. Order one or outfit a floor.">Solid wood tops, quiet motors, a ten-year warranty. Order one or outfit a floor.</p>
6
+ <div class="hero-actions">
7
+ <a href="/desk" class="btn btn-dark btn-lg" data-sqid-label="shop_desks" data-sqid-type="key_event">Shop desks</a>
8
+ <a href="/pricing" class="btn btn-ghost btn-lg" data-sqid-label="team_pricing" data-sqid-type="key_event">Team pricing</a>
9
+ </div>
10
+ </div>
11
+ <div class="hero-art" aria-hidden="true"><div class="desk"><span class="leg"></span><span class="leg"></span></div></div>
12
+ </section>
13
+
14
+ <section class="wrap tiles">
15
+ <a href="/pricing" class="tile"><strong>Pricing</strong><span>Linger here and come back. Deliberation looks like this.</span></a>
16
+ <a href="/desk" class="tile"><strong>A desk with options</strong><span>Switch sizes and finishes. That is the variants signal.</span></a>
17
+ <a href="/demo" class="tile"><strong>Book a demo</strong><span>Prefilled from the profile. Stop halfway for a form stall.</span></a>
18
+ </section>
19
+
20
+ <section class="wrap band">
21
+ <div class="band-inner">
22
+ <h2>Trusted by teams that stand up for themselves</h2>
23
+ <p>Northwind Robotics, Brightlane Analytics, Orchard Pay, Halcyon Labs and a few hundred more. (All made up, like everything here.)</p>
24
+ </div>
25
+ </section>
@@ -0,0 +1,29 @@
1
+ <section class="wrap pricing">
2
+ <div class="center">
3
+ <h1 id="pricing-title" data-default="Pricing">Pricing</h1>
4
+ <p id="pricing-sub" data-default="One desk or a whole floor. Volume pricing from ten desks.">One desk or a whole floor. Volume pricing from ten desks.</p>
5
+ <span class="pill hidden" id="pricing-pill">Personalised by the Pricing recipe</span>
6
+ </div>
7
+ <div class="plans">
8
+ <div class="plan" id="plan-starter">
9
+ <span class="plan-name">Starter</span>
10
+ <span class="plan-price">$749<small> / desk</small></span>
11
+ <span class="plan-desc">1 to 9 desks. Free shipping.</span>
12
+ <a href="/desk" class="btn btn-ghost" data-sqid-label="plan_starter" data-sqid-type="key_event">Choose</a>
13
+ </div>
14
+ <div class="plan" id="plan-team">
15
+ <span class="plan-badge hidden" id="plan-team-badge">FOR YOUR TEAM SIZE</span>
16
+ <span class="plan-name">Team</span>
17
+ <span class="plan-price">$629<small> / desk</small></span>
18
+ <span class="plan-desc">10 to 200 desks. Account manager, installation.</span>
19
+ <a href="/demo" class="btn btn-dark" data-sqid-label="plan_team" data-sqid-type="key_event">Talk to sales</a>
20
+ </div>
21
+ <div class="plan" id="plan-enterprise">
22
+ <span class="plan-name">Enterprise</span>
23
+ <span class="plan-price">Custom</span>
24
+ <span class="plan-desc">200+ desks, multi-site rollouts.</span>
25
+ <a href="/demo" class="btn btn-ghost" data-sqid-label="plan_enterprise" data-sqid-type="key_event">Contact us</a>
26
+ </div>
27
+ </div>
28
+ <p class="hint center">Leave and come back to this page a few times. On a real site with Signals on, that pattern becomes a deliberation moment.</p>
29
+ </section>
@@ -0,0 +1,13 @@
1
+ <section class="wrap two-col">
2
+ <div>
3
+ <h1>Sign in</h1>
4
+ <p>When someone signs in, your site already knows who they are. Tell Sqid with one call and the visitor is bound to that identity from now on.</p>
5
+ <pre class="code">await squid.identify({ email });</pre>
6
+ <p class="hint">Any email works here. Use one of the Sandbox's test people (the panel's Scenarios tab lists who you are) or your own.</p>
7
+ </div>
8
+ <form class="card-form" action="/signin" method="post" id="signin-form">
9
+ <label>Email<input name="email" type="email" autocomplete="off" required placeholder="you@company.com"></label>
10
+ <label>Password<input name="password" type="password" autocomplete="off" placeholder="anything"></label>
11
+ <button type="submit" class="btn btn-dark btn-lg" data-sqid-label="sign_in" data-sqid-type="conversion">Sign in</button>
12
+ </form>
13
+ </section>
@@ -0,0 +1,11 @@
1
+ <section class="wrap">
2
+ <span class="eyebrow">FOR TEAMS</span>
3
+ <h1 id="teams-title" data-default="Outfit a floor without a spreadsheet.">Outfit a floor without a spreadsheet.</h1>
4
+ <p class="lede">One order, one delivery window, one person to call. Volume pricing from ten desks, installation included from fifty.</p>
5
+ <div class="tiles">
6
+ <div class="tile"><strong>Account manager</strong><span>One person who knows your floor plan.</span></div>
7
+ <div class="tile"><strong>Installation</strong><span>Assembled, levelled, cables managed.</span></div>
8
+ <div class="tile"><strong>Net 30</strong><span>Invoice billing for teams of fifty or more.</span></div>
9
+ </div>
10
+ <div class="hero-actions"><a href="/demo" class="btn btn-dark btn-lg" data-sqid-label="teams_demo" data-sqid-type="key_event">Book a demo</a><a href="/pricing" class="btn btn-ghost btn-lg">See pricing</a></div>
11
+ </section>
package/src/server.js ADDED
@@ -0,0 +1,65 @@
1
+ // The Driftwood site plus the panel's small local API under /_sqid. Everything under /_sqid talks
2
+ // to Sqid through the Bridge with the signed-in person's own credentials; nothing is stored here.
3
+
4
+ import express from 'express';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { render, PAGES } from './layout.js';
8
+ import { localRecord } from './sqid.js';
9
+
10
+ const here = path.dirname(fileURLToPath(import.meta.url));
11
+
12
+ export function createApp(bridge){
13
+ let app = express();
14
+ app.disable('x-powered-by');
15
+ app.use(express.json({ limit : '64kb' }));
16
+ app.use(express.urlencoded({ extended : false }));
17
+ app.use('/assets', express.static(path.join(here, '..', 'public'), { maxAge : 0 }));
18
+
19
+ // Only this machine talks to the local API (the site itself is fine to open from anywhere on the LAN).
20
+ app.use('/_sqid', (req, res, next) => {
21
+ let host = String(req.headers.host || '').split(':')[0];
22
+ if(!['localhost', '127.0.0.1', '[::1]', '::1'].includes(host)){ return res.status(403).json({ error : 'local_only' }); }
23
+ next();
24
+ });
25
+
26
+ app.get('/_sqid/state', wrap(async () => bridge.state()));
27
+ app.get('/_sqid/sample', wrap(async (req) => bridge.sample(req.query.event || 'identification')));
28
+ app.get('/_sqid/visitors/:id', wrap(async (req) => bridge.visitor(req.params.id)));
29
+ app.get('/_sqid/visitors/:id/events', wrap(async (req) => bridge.visitorEvents(req.params.id)));
30
+ app.get('/_sqid/webhooks', wrap(async () => bridge.webhooks()));
31
+ app.post('/_sqid/webhooks', wrap(async (req) => {
32
+ let url = String(req.body?.url || '').trim();
33
+ if(!/^https:\/\//i.test(url)){ throw Object.assign(new Error('The endpoint must be an https URL'), { status : 400 }); }
34
+ await bridge.addWebhook(url, req.body?.event || 'identification');
35
+ return { ok : true, webhooks : await bridge.webhooks() };
36
+ }));
37
+ app.post('/_sqid/webhooks/:id/test', wrap(async (req) => bridge.testWebhook(req.params.id)));
38
+ app.post('/_sqid/sites', wrap(async (req) => bridge.createSite({ name : String(req.body?.name || '').slice(0, 50), url : String(req.body?.url || '') })));
39
+ app.get('/_sqid/sites/:id/status', wrap(async (req) => bridge.siteStatus(req.params.id)));
40
+
41
+ // The service-provider recipe: what "your database" adds to the profile. Sqid POSTs the traits here.
42
+ app.post('/_sqid/sp/visitor_details', (req, res) => res.json(localRecord(req.body || {})));
43
+
44
+ // The site
45
+ for(let [route, page] of Object.entries(PAGES)){
46
+ app.get(route, (req, res) => res.type('html').send(render(page, { bridge, path : route, query : req.query })));
47
+ }
48
+ app.post('/cart/add', (req, res) => res.redirect(303, '/cart?added=1'));
49
+ app.post('/demo', (req, res) => res.redirect(303, '/demo?sent=1'));
50
+ app.post('/signin', (req, res) => res.redirect(303, `/?signed_in=1&email=${encodeURIComponent(String(req.body?.email || ''))}`));
51
+ app.post('/cart/checkout', (req, res) => res.redirect(303, '/cart?ordered=1'));
52
+
53
+ app.use((req, res) => res.status(404).type('html').send(render('notfound', { bridge, path : req.path, query : {} })));
54
+ return app;
55
+ }
56
+
57
+ function wrap(fn){
58
+ return async (req, res) => {
59
+ try{ res.json(await fn(req) ?? null); }
60
+ catch(error){
61
+ let status = error?.status || (error?.code === 'unauthorized' ? 401 : 500);
62
+ res.status(status).json({ error : error?.code || 'error', message : error?.message || String(error), remedy : error?.remedy || undefined });
63
+ }
64
+ };
65
+ }
package/src/sqid.js ADDED
@@ -0,0 +1,167 @@
1
+ // The bridge to the person's Sqid account. Everything the panel needs from Sqid goes through
2
+ // here, with the sqid CLI's own modules (credentials, API, site resolution, SDK keys), so the
3
+ // playground never holds a second copy of auth. Nothing is cached across runs except what the
4
+ // CLI already keeps in ~/.config/sqid/credentials.json.
5
+
6
+ import os from 'node:os';
7
+ import { api } from '@sqid-dev/sqid/src/api.js';
8
+ import { readCredentials, writeCredentials } from '@sqid-dev/sqid/src/credentials.js';
9
+ import { siteRow, snippetFor, toOrigins } from '@sqid-dev/sqid/src/project.js';
10
+ import { EVENTS } from '@sqid-dev/sqid/src/commands/webhook.js';
11
+ import { loginLoopback, userinfo } from '@sqid-dev/sqid/src/oauth.js';
12
+
13
+ const base = (site, ev) => `${ev.v2 ? '/api/v2' : '/api'}/projects/${site.id}`;
14
+
15
+ // Sites with their allowed origins (the CLI's siteRow leaves origins out).
16
+ async function listSites(flags){
17
+ let rows = await api('GET', '/api/sqid/projects', { flags });
18
+ return (rows || []).map(p => ({ ...siteRow(p), origins : (p.site_origins || []).map(String) }));
19
+ }
20
+
21
+ export class Bridge {
22
+ constructor(flags = {}){
23
+ this.flags = flags;
24
+ this.site = null;
25
+ this.me = null;
26
+ }
27
+
28
+ // Sign in if needed, pick the site, allow this origin on it.
29
+ async prepare(origin){
30
+ let creds = await readCredentials();
31
+ if(!creds?.access_token){
32
+ process.stdout.write(' Not signed in to Sqid. Opening your browser to sign in...\n');
33
+ let tokens = await loginLoopback({ onUrl : (url, { opened }) => process.stdout.write(opened ? ` If it did not open: ${url}\n` : ` Open this link to sign in: ${url}\n`) });
34
+ let info = await userinfo(tokens.access_token).catch(() => null);
35
+ await writeCredentials({ ...tokens, email : info?.email, user_id : info?.sub || info?.user_id, issued_on : os.hostname(), issued_at : new Date().toISOString() });
36
+ creds = await readCredentials();
37
+ }
38
+ this.me = await api('GET', '/api/sqid/me', { flags : this.flags });
39
+
40
+ let sites = await listSites(this.flags);
41
+ let site = this.flags.site ? sites.find(s => s.id === this.flags.site || s.name === this.flags.site) : sites.find(s => s.sandbox);
42
+ if(this.flags.site && !site){ throw Object.assign(new Error(`No site "${this.flags.site}" on this account.`), { exit : 2 }); }
43
+ if(!site){
44
+ // The account has no Sandbox (deleted, or an older account): make it again.
45
+ let made = await api('POST', '/api/sqid/sandbox', { flags : this.flags, body : {} });
46
+ sites = await listSites(this.flags);
47
+ site = sites.find(s => s.id === String(made?.sdk_id)) || sites.find(s => s.sandbox);
48
+ if(!site){ throw new Error('Sqid did not return a Sandbox site.'); }
49
+ }
50
+ this.site = site;
51
+
52
+ // Allow this origin on the site (the snippet loads nothing from an origin the site does not list).
53
+ let originAdded = false;
54
+ let current = (site.origins || []).map(String);
55
+ if(!current.includes(origin)){
56
+ let next = toOrigins([...current, origin].join(','));
57
+ await api('PATCH', `/api/projects/${site.id}`, { flags : this.flags, body : { name : site.name, site_origins : next, product_origins : next } });
58
+ this.site = { ...site, origins : next };
59
+ originAdded = true;
60
+ }
61
+ return { email : this.me?.email || this.me?.user?.email || creds?.email || 'you', site : this.site, originAdded };
62
+ }
63
+
64
+ snippet(id = this.site.id){ return snippetFor(id); }
65
+
66
+ // What the panel's Start tab needs, in one call.
67
+ async state(){
68
+ let [me, hooks] = await Promise.all([
69
+ api('GET', '/api/sqid/me', { flags : this.flags }).catch(() => this.me),
70
+ this.webhooks().catch(() => [])
71
+ ]);
72
+ this.me = me || this.me;
73
+ return {
74
+ email : me?.email || me?.user?.email || null,
75
+ plan : { has : !!me?.account?.hasSubscription, name : me?.account?.plan?.name || me?.billing?.plan || null, card : !!(me?.billing?.card || me?.account?.card) },
76
+ features : me?.features || {},
77
+ site : { id : this.site.id, name : this.site.name, sandbox : !!this.site.sandbox, origins : this.site.origins || [] },
78
+ snippet : this.snippet(),
79
+ webhooks : hooks,
80
+ console : this.flags.api || 'https://app.sqid.dev'
81
+ };
82
+ }
83
+
84
+ async webhooks(){
85
+ let r = await api('GET', `/api/sqid/sdks/${this.site.id}/webhooks`, { flags : this.flags });
86
+ let list = Array.isArray(r) ? r : r?.webhooks || [];
87
+ return list.map(w => ({ id : String(w._id || w.id), url : w.url, event : w.namespace || w.event, enabled : w.enabled !== false, health : w.health || null, name : w.name || null }));
88
+ }
89
+
90
+ async addWebhook(url, eventKey = 'identification'){
91
+ let ev = EVENTS[eventKey] || EVENTS.identification;
92
+ return api('POST', `${base(this.site, ev)}/webhook`, { flags : this.flags, body : { url, namespace : ev.namespace, name : 'Playground' } });
93
+ }
94
+
95
+ async testWebhook(id){
96
+ let hooks = await this.webhooks();
97
+ let w = hooks.find(h => h.id === id);
98
+ if(!w){ throw Object.assign(new Error('No such webhook'), { status : 404 }); }
99
+ let ev = Object.values(EVENTS).find(e => e.namespace === w.event) || EVENTS.identification;
100
+ return api('POST', `${base(this.site, ev)}/webhook/test`, { flags : this.flags, body : { webhook_id : id } });
101
+ }
102
+
103
+ // A sample of the record a webhook delivers (nothing is sent).
104
+ async sample(eventKey = 'identification'){
105
+ let ev = EVENTS[eventKey] || EVENTS.identification;
106
+ let r = await api('POST', `${base(this.site, ev)}/webhook/preview`, { flags : this.flags, body : { namespace : ev.namespace } });
107
+ return r?.payload || r;
108
+ }
109
+
110
+ // The live visitor's full profile, the same record the console's Identities page shows (the
111
+ // public visitor API does not index Sandbox people, so this goes through the console route).
112
+ async visitor(id){
113
+ if(!/^[a-f0-9]{24}$/i.test(String(id))){ throw Object.assign(new Error('not a visitor id'), { status : 400 }); }
114
+ let r = await api('GET', `/api/projects/${this.site.id}/profiles/${id}`, { flags : this.flags });
115
+ if(!r){ throw Object.assign(new Error('not found'), { status : 404 }); }
116
+ let { seen_by, pinned_by, __v, ...rest } = r;
117
+ return rest;
118
+ }
119
+
120
+ async visitorEvents(id){
121
+ if(!/^[a-f0-9]{24}$/i.test(String(id))){ return { error : 'not a visitor id' }; }
122
+ return api('GET', `/api/projects/${this.site.id}/profiles/${id}/key-events`, { flags : this.flags }).catch(e => ({ error : e.message }));
123
+ }
124
+
125
+ // Go live: a real site on the account, with its snippet.
126
+ async createSite({ name, url }){
127
+ let origins = toOrigins(url);
128
+ if(!origins.length){ throw Object.assign(new Error('Give the site\'s public URL, e.g. https://www.example.com'), { status : 400 }); }
129
+ let me = await api('GET', '/api/sqid/me', { flags : this.flags });
130
+ if(!me?.account?.hasSubscription){
131
+ try{ await api('POST', '/api/sqid/billing/start', { flags : this.flags, body : {} }); }catch(error){ /* the project route starts it too */ }
132
+ }
133
+ let sites = await listSites(this.flags);
134
+ let same = sites.find(s => !s.sandbox && s.name?.toLowerCase() === String(name || '').toLowerCase());
135
+ let site = same;
136
+ if(!site){
137
+ let created = await api('POST', '/api/projects', { flags : this.flags, body : { name : name || new URL(origins[0]).hostname, site_origins : origins, product_origins : origins, avatar_index : 1 } });
138
+ let id = String(created?._id || created?.id || created?.sdk_id || '');
139
+ sites = await listSites(this.flags);
140
+ site = sites.find(s => s.id === id) || sites.find(s => !s.sandbox && s.origins?.includes(origins[0]));
141
+ }
142
+ if(!site){ throw new Error('Sqid did not return the new site.'); }
143
+ return { site, snippet : snippetFor(site.id), origins };
144
+ }
145
+
146
+ async siteStatus(id){
147
+ let sites = await listSites(this.flags);
148
+ let s = sites.find(x => x.id === id);
149
+ return s ? { id : s.id, name : s.name, deployed : !!s.deployed, connected : !!s.connected } : null;
150
+ }
151
+ }
152
+
153
+ // Deterministic "your database" for the service-provider recipe: what a customer's own backend
154
+ // would add to a Sqid profile. Keyed on the email so the same fixture person always gets the same answer.
155
+ export function localRecord(traits = {}){
156
+ let email = String(traits.email || '').toLowerCase();
157
+ let n = [...email].reduce((a, c) => (a * 31 + c.charCodeAt(0)) >>> 0, 7);
158
+ let plans = ['Starter', 'Team', 'Team', 'Enterprise'];
159
+ return {
160
+ ...traits,
161
+ accountType : plans[n % plans.length],
162
+ customerSince : `${2021 + (n % 5)}-0${1 + (n % 9)}-1${n % 9}`,
163
+ lifetimeValue : 749 * (1 + (n % 40)),
164
+ openTickets : n % 3,
165
+ source : 'your database (mock)'
166
+ };
167
+ }