@framestudio/keel-sdk 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,27 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First release. Extracted from the hand-copied `keelClient.js` that every custom
6
+ site had grown separately — five copies, already drifted.
7
+
8
+ - `createClient({ token, apiBase? })` with products, catalogue, services,
9
+ settings, banners, page content and inquiries.
10
+ - Normalisers for every response, so a site renders the same shape whatever the
11
+ API sends: numbers coerced, `null` preserved as "not set", `stock: null` is
12
+ "not tracked" rather than "out of stock".
13
+ - `KeelError` with a `code` (`no_token`, `unauthorized`, `forbidden`,
14
+ `not_found`, `rate_limited`, `network`, `server`) so a site can tell "the API
15
+ is down" from "nothing matched".
16
+ - Retry budget of 4s × 2 with 500ms backoff; 4xx is not retried.
17
+ - `@framestudio/keel-analytics` re-exported, so a site installs one package.
18
+ - Optional React bindings at `@framestudio/keel-sdk/react`.
19
+ - Embed script for sites with no build step (`src/embed.js`, built to a single
20
+ IIFE and hosted by the dashboard).
21
+
22
+ ### Deliberately not here
23
+
24
+ - No caching layer. A site's framework already has one, and a second cache is how
25
+ "I published it but my site is stale" happens.
26
+ - No server-side rendering helpers. Both live sites fetch on the client.
27
+ - No dependency on a specific UI stack.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FrameStudio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,186 @@
1
- # Temporary Holding Version
1
+ # @framestudio/keel-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Read a Keel shop's catalogue, services, settings and content from a custom
4
+ website — with one publishable key and no database credential in the browser.
5
+
6
+ ```bash
7
+ npm install @framestudio/keel-sdk
8
+ ```
9
+
10
+ ```js
11
+ import { createClient } from '@framestudio/keel-sdk'
12
+
13
+ const keel = createClient({ token: import.meta.env.VITE_KEEL_SITE_TOKEN })
14
+
15
+ const products = await keel.products()
16
+ ```
17
+
18
+ That is the whole setup. The key comes from **Keel → Settings → Developer**;
19
+ copy the publishable one into the site's build (Vercel, Netlify, `.env`).
20
+
21
+ ---
22
+
23
+ ## What the token is
24
+
25
+ A **publishable** credential. It ships in your site's JavaScript, so anyone can
26
+ read it — that is expected, and it is why the API decides what it may reach
27
+ rather than trusting the client. It identifies the shop and it is rate-limited.
28
+
29
+ Never treat it as a password, and never put it in a URL: query strings land in
30
+ access logs, browser history and `Referer` headers, where a credential outlives
31
+ the request that carried it. This package always sends it as a header.
32
+
33
+ ---
34
+
35
+ ## Methods
36
+
37
+ | Call | Returns | Notes |
38
+ |---|---|---|
39
+ | `keel.products()` | `Product[]` | Inventory, with stock |
40
+ | `keel.catalogue()` | `CatalogueItem[]` | What the site shows — products **and** services |
41
+ | `keel.services()` | `Service[]` | Priced per job, with a unit |
42
+ | `keel.settings()` | `Settings` | Name, contact, hours, colours, feature switches |
43
+ | `keel.banners()` | `Banner[]` | Active ones, already ordered |
44
+ | `keel.pageContent({ page?, section? })` | `PageSection[]` | Copy blocks; `[]` if neither is given |
45
+ | `keel.inquire({ name, phone, message? })` | `{ ok: true }` | Needs the `inquiry` scope |
46
+ | `keel.request(path, opts)` | raw JSON | Escape hatch |
47
+
48
+ Every list is normalised: numbers coerced, `null` kept as "not set", and no
49
+ `cost_price` anywhere (a product never exposes what the shop paid).
50
+
51
+ ### Shapes worth knowing
52
+
53
+ ```js
54
+ // CatalogueItem.type is the discriminator the whole page branches on
55
+ { type: 'product' } // has specs, availability, stock via the linked product
56
+ { type: 'service' } // priced per job, has includes, no stock
57
+
58
+ // Service.pricingMode — quote it, do not flatten it
59
+ 'flat' | 'per_unit' | 'per_weight' | 'per_hour'
60
+
61
+ // Product.stock: null means "not tracked", which is NOT out of stock
62
+ { stock: null, inStock: true }
63
+ { stock: 0, inStock: false }
64
+ ```
65
+
66
+ ---
67
+
68
+ ## Errors
69
+
70
+ Failures throw `KeelError` with a `code` you can branch on:
71
+
72
+ | `code` | Meaning | What to show |
73
+ |---|---|---|
74
+ | `no_token` | No key configured | "This site isn't connected yet" |
75
+ | `unauthorized` | Key rejected or revoked | Same — do not retry |
76
+ | `forbidden` | Key lacks the scope | A developer problem, not a visitor one |
77
+ | `not_found` | Wrong shop | Setup error |
78
+ | `rate_limited` | Too many requests | Try again shortly |
79
+ | `network` | Offline, DNS, timeout | **"Can't reach the shop right now"** |
80
+ | `server` | The API failed | Same as above |
81
+
82
+ **Keep `network`/`server` separate from an empty result.** "The API is down" and
83
+ "your filters matched nothing" are different screens; collapsing them into
84
+ "No products found" `<!-- -->` is the most common defect in these sites, and it
85
+ hides outages from the person who could fix them.
86
+
87
+ ```js
88
+ try {
89
+ setProducts(await keel.products())
90
+ } catch (err) {
91
+ setError(err.code === 'network' || err.code === 'server' ? 'offline' : 'failed')
92
+ }
93
+ ```
94
+
95
+ ### Retries
96
+
97
+ `4s × 2` with a 500ms backoff. The API host sleeps when idle, so a cold start is
98
+ normal rather than exceptional — but a storefront that shows nothing for half a
99
+ minute reads as broken. 4xx responses are **not** retried: the same answer costs
100
+ another second of the visitor's time.
101
+
102
+ ---
103
+
104
+ ## React
105
+
106
+ ```jsx
107
+ import { KeelProvider, useProducts, useShopSettings } from '@framestudio/keel-sdk/react'
108
+ import { createClient } from '@framestudio/keel-sdk'
109
+
110
+ const client = createClient({ token })
111
+
112
+ export default function App() {
113
+ return (
114
+ <KeelProvider client={client}>
115
+ <Shop />
116
+ </KeelProvider>
117
+ )
118
+ }
119
+
120
+ function Shop() {
121
+ const { data: products, error, loading } = useProducts()
122
+ if (loading) return <Skeleton />
123
+ if (error) return <Offline />
124
+ return products.map((p) => <Card key={p.id} product={p} />)
125
+ }
126
+ ```
127
+
128
+ `react` is an optional peer dependency; the core has none.
129
+
130
+ ---
131
+
132
+ ## Embed on a site with no build step
133
+
134
+ For a Wix page, a WordPress theme, or a single hand-written `index.html`:
135
+
136
+ ```html
137
+ <div data-keel-catalogue data-keel-token="pk_site_…" data-keel-limit="12"></div>
138
+ <script src="https://keel.framestudio.co.ke/keel.js" defer></script>
139
+ ```
140
+
141
+ The token is the publishable key from **Keel → Settings → Developer**. Nothing else
142
+ to configure: the grid renders itself, and an "Ask on WhatsApp" button appears
143
+ when the shop has a WhatsApp number.
144
+
145
+ The script is built from this package (`npm run build:embed`) and copied to the
146
+ dashboard's `public/keel.js`, which Vercel serves. **Do not edit the built file** —
147
+ edit `src/embed.js` and rebuild. It is deliberately *not* served by `keel-api`,
148
+ which sleeps when idle and would be unavailable exactly when the embed is needed.
149
+
150
+ Deliberate limits: a read-only grid. No cart, no variants, no detail page. A site
151
+ that needs those is a bespoke build with this package installed, not a script tag.
152
+
153
+ ---
154
+
155
+ ## Analytics
156
+
157
+ The analytics SDK is re-exported, so one package covers both:
158
+
159
+ ```js
160
+ import { createClient, init, track } from '@framestudio/keel-sdk'
161
+
162
+ createClient({ token })
163
+ init({ token }) // page views and errors report themselves
164
+ track('add_to_cart', { name: 'Kikoi', quantity: 1 })
165
+ ```
166
+
167
+ ---
168
+
169
+ ## Testing
170
+
171
+ ```bash
172
+ npm test # node --test, no network
173
+ ```
174
+
175
+ The client tests inject `fetch`, so they never touch a real shop.
176
+
177
+ ---
178
+
179
+ ## Publishing
180
+
181
+ ```bash
182
+ npm publish --access public
183
+ ```
184
+
185
+ Sites pin a version deliberately: with several live storefronts, a release should
186
+ never reach them unannounced.
package/client.js ADDED
@@ -0,0 +1,184 @@
1
+ import {
2
+ normalizeBanner,
3
+ normalizeCatalogueItem,
4
+ normalizePageContent,
5
+ normalizeProduct,
6
+ normalizeService,
7
+ normalizeSettings,
8
+ } from './normalize.js'
9
+
10
+ /**
11
+ * The client every custom site talks to Keel through.
12
+ *
13
+ * The token is a PUBLISHABLE credential: it ships in the site's own JavaScript,
14
+ * so its safety comes from what the API lets it reach, never from secrecy. It
15
+ * identifies the shop and it is rate-limited; it is not a password, and nothing
16
+ * here should be treated as if it were.
17
+ *
18
+ * The analytics SDK is re-exported so a site installs one package:
19
+ *
20
+ * import { createClient, init, track } from '@framestudio/keel-sdk'
21
+ */
22
+
23
+ export * from '@framestudio/keel-analytics'
24
+
25
+ /** Matches the default in `@framestudio/keel-analytics`. */
26
+ export const API_BASE = 'https://keel-api-37rh.onrender.com'
27
+
28
+ /**
29
+ * 4s × 2 with a 500ms backoff.
30
+ *
31
+ * Copied deliberately from the kikoi storefront, which measured the alternative:
32
+ * 10s × 3 with 1s/2s backoff meant a slow (not refused) API cost about 33 seconds
33
+ * of skeleton before a visitor saw anything. The API host sleeps when idle, so a
34
+ * cold start is the normal case rather than the exceptional one — and a storefront
35
+ * that shows nothing for half a minute reads as broken, not as slow.
36
+ */
37
+ const TIMEOUT_MS = 4000
38
+ const ATTEMPTS = 2
39
+ const BACKOFF_MS = 500
40
+
41
+ export class KeelError extends Error {
42
+ constructor(message, { code = 'error', status = 0, cause } = {}) {
43
+ super(message)
44
+ this.name = 'KeelError'
45
+ this.code = code
46
+ this.status = status
47
+ this.cause = cause
48
+ }
49
+ }
50
+
51
+ function codeForStatus(status) {
52
+ if (status === 401) return 'unauthorized'
53
+ if (status === 403) return 'forbidden'
54
+ if (status === 404) return 'not_found'
55
+ if (status === 429) return 'rate_limited'
56
+ if (status >= 500) return 'server'
57
+ return 'error'
58
+ }
59
+
60
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
61
+
62
+ export function createClient({
63
+ token,
64
+ apiBase = API_BASE,
65
+ fetch: fetchImpl,
66
+ timeoutMs = TIMEOUT_MS,
67
+ attempts = ATTEMPTS,
68
+ backoffMs = BACKOFF_MS,
69
+ } = {}) {
70
+ const doFetch = fetchImpl || (typeof fetch === 'function' ? fetch.bind(globalThis) : null)
71
+ const base = String(apiBase).replace(/\/+$/, '')
72
+
73
+ /**
74
+ * One authenticated call.
75
+ *
76
+ * The token goes in a header and never in the query string: query strings end
77
+ * up in access logs, browser history and Referer headers, where a credential
78
+ * outlives the request that carried it.
79
+ */
80
+ async function request(path, { method = 'GET', body } = {}) {
81
+ if (!token) {
82
+ throw new KeelError('No site token configured. Pass `token` to createClient.', {
83
+ code: 'no_token',
84
+ })
85
+ }
86
+ if (!doFetch) {
87
+ throw new KeelError('No fetch available in this environment.', { code: 'no_fetch' })
88
+ }
89
+
90
+ let lastError = null
91
+
92
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
93
+ const controller = typeof AbortController === 'function' ? new AbortController() : null
94
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null
95
+
96
+ let response = null
97
+ try {
98
+ response = await doFetch(`${base}${path}`, {
99
+ method,
100
+ headers: {
101
+ 'x-keel-site-token': token,
102
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
103
+ },
104
+ body: body ? JSON.stringify(body) : undefined,
105
+ signal: controller ? controller.signal : undefined,
106
+ })
107
+ } catch (cause) {
108
+ // Abort, DNS failure, offline — the visitor gets one more try, then an
109
+ // error they can be shown. Nothing here throws at the host app.
110
+ lastError = new KeelError('Could not reach the shop', { code: 'network', cause })
111
+ response = null
112
+ } finally {
113
+ if (timer) clearTimeout(timer)
114
+ }
115
+
116
+ if (response) {
117
+ if (response.ok) return await response.json()
118
+
119
+ const error = new KeelError(`Request failed (${response.status})`, {
120
+ code: codeForStatus(response.status),
121
+ status: response.status,
122
+ })
123
+
124
+ // A 4xx is a fact about the request: retrying spends a second of the
125
+ // visitor's patience to be told the same thing. 429 and 5xx are weather.
126
+ const retryable = response.status >= 500 || response.status === 429
127
+ if (!retryable) throw error
128
+
129
+ lastError = error
130
+ }
131
+
132
+ if (attempt < attempts) await sleep(backoffMs * attempt)
133
+ }
134
+
135
+ throw lastError || new KeelError('Request failed', { code: 'error' })
136
+ }
137
+
138
+ return {
139
+ /** Whether a token was supplied. Never the token itself. */
140
+ configured: Boolean(token),
141
+
142
+ products: async () => (await request('/api/products')).map(normalizeProduct),
143
+
144
+ catalogue: async () => (await request('/api/catalogue')).map(normalizeCatalogueItem),
145
+
146
+ services: async () => (await request('/api/services')).map(normalizeService),
147
+
148
+ banners: async () => (await request('/api/banners')).map(normalizeBanner),
149
+
150
+ settings: async () => normalizeSettings(await request('/api/settings')),
151
+
152
+ /**
153
+ * `page` addresses the legacy model (page + section); `section` on its own
154
+ * addresses the newer one. The API returns an empty array when neither is
155
+ * given rather than dumping every row.
156
+ */
157
+ pageContent: async ({ page, section } = {}) => {
158
+ const query = new URLSearchParams()
159
+ if (page) query.set('page', page)
160
+ if (section) query.set('section', section)
161
+ const suffix = query.toString() ? `?${query}` : ''
162
+ const rows = await request(`/api/page-content${suffix}`)
163
+ return Array.isArray(rows) ? rows.map(normalizePageContent) : []
164
+ },
165
+
166
+ /**
167
+ * Send a customer message from a contact form.
168
+ *
169
+ * Requires the `inquiry` scope. The API takes the shop and the site from the
170
+ * token — passing either in the body is ignored, so a site cannot file a
171
+ * message against another shop.
172
+ */
173
+ inquire: async ({ name, phone, email, message, productRef } = {}) => {
174
+ const payload = { name, phone }
175
+ if (email) payload.email = email
176
+ if (message) payload.message = message
177
+ if (productRef) payload.product_ref = productRef
178
+ return request('/api/inquiries', { method: 'POST', body: payload })
179
+ },
180
+
181
+ /** Escape hatch. Same credential, same retry budget, no normalising. */
182
+ request,
183
+ }
184
+ }
package/normalize.js ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * What the API returns, turned into what a site needs to render.
3
+ *
4
+ * Every field here exists on the endpoint named above the function. That is not
5
+ * a stylistic choice: a normaliser that reads `raw.costPrice` against a response
6
+ * that carries `cost_price` silently returns undefined, and the site renders a
7
+ * blank price with no error anywhere. So each function documents the columns it
8
+ * is allowed to see, and nothing is invented.
9
+ */
10
+
11
+ /** Postgres `numeric` arrives as a string; `Number('')` is 0, which is a lie. */
12
+ function toNumber(value) {
13
+ if (value === null || value === undefined || value === '') return null;
14
+ const n = Number(value);
15
+ return Number.isFinite(n) ? n : null;
16
+ }
17
+
18
+ function toString(value, fallback = '') {
19
+ return typeof value === 'string' ? value : value === null || value === undefined ? fallback : String(value);
20
+ }
21
+
22
+ function toArray(value) {
23
+ return Array.isArray(value) ? value : [];
24
+ }
25
+
26
+ /**
27
+ * GET /api/products
28
+ * columns: id, name, category, price, stock, barcode, image, created_at
29
+ *
30
+ * Note what is absent: the endpoint used to publish `cost_price`, so the shop's
31
+ * buying price and margin were readable from the storefront's own JavaScript.
32
+ * The normaliser never looks for it — a site prices from `price`.
33
+ */
34
+ export function normalizeProduct(raw = {}) {
35
+ const stock = toNumber(raw.stock);
36
+ return {
37
+ id: raw.id ?? null,
38
+ name: toString(raw.name, 'Untitled'),
39
+ category: toString(raw.category),
40
+ price: toNumber(raw.price),
41
+ stock,
42
+ // A null stock means the shop does not track it; that is not "out of stock".
43
+ inStock: stock === null ? true : stock > 0,
44
+ barcode: raw.barcode || null,
45
+ image: raw.image || null,
46
+ createdAt: raw.created_at || null,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * GET /api/catalogue
52
+ * columns: id, name, type, category, price, price_label, description, image,
53
+ * available, featured, variants, specs, includes, new_arrival,
54
+ * sale_price, sale_ends_at, badge, badge_ends_at, product_id, created_at
55
+ *
56
+ * `type` is the discriminator the whole site branches on: a service is priced
57
+ * per job and has "what's included", a product has specs and stock.
58
+ */
59
+ export function normalizeCatalogueItem(raw = {}) {
60
+ return {
61
+ id: raw.id ?? null,
62
+ name: toString(raw.name, 'Untitled'),
63
+ type: raw.type === 'service' ? 'service' : 'product',
64
+ category: toString(raw.category),
65
+ price: toNumber(raw.price),
66
+ salePrice: toNumber(raw.sale_price),
67
+ priceLabel: raw.price_label || null,
68
+ description: toString(raw.description),
69
+ image: raw.image || null,
70
+ available: raw.available !== false,
71
+ featured: raw.featured === true,
72
+ newArrival: raw.new_arrival === true,
73
+ badge: raw.badge || null,
74
+ variants: raw.variants ?? null,
75
+ specs: raw.specs ?? null,
76
+ includes: toArray(raw.includes),
77
+ // Set when the row is the published form of an inventory product: one button,
78
+ // one price, one stock rule.
79
+ productId: raw.product_id || null,
80
+ createdAt: raw.created_at || null,
81
+ };
82
+ }
83
+
84
+ const PRICING_MODES = ['flat', 'per_unit', 'per_weight', 'per_hour'];
85
+
86
+ /**
87
+ * GET /api/services
88
+ * columns: id, category, name, pricing_mode, price, unit_label, description,
89
+ * turnaround_hours, image
90
+ *
91
+ * `pricingMode` is not decoration. A laundry priced per kilo quoted as a flat
92
+ * "KSh 300" is a price the customer acts on and is wrong about.
93
+ */
94
+ export function normalizeService(raw = {}) {
95
+ return {
96
+ id: raw.id ?? null,
97
+ name: toString(raw.name, 'Untitled'),
98
+ category: toString(raw.category),
99
+ price: toNumber(raw.price),
100
+ pricingMode: PRICING_MODES.includes(raw.pricing_mode) ? raw.pricing_mode : 'flat',
101
+ unitLabel: raw.unit_label || null,
102
+ description: toString(raw.description),
103
+ turnaroundHours: toNumber(raw.turnaround_hours),
104
+ image: raw.image || null,
105
+ };
106
+ }
107
+
108
+ /**
109
+ * GET /api/settings
110
+ * columns: shop_id, store_name, description, about, tagline, store_phone,
111
+ * whatsapp, store_address, business_hours, currency_symbol, logo_url,
112
+ * instagram, facebook, tiktok, primary_color, secondary_color,
113
+ * accent_color, name_accent, featured_product_ids, website_url,
114
+ * feature_toggles
115
+ *
116
+ * `features` is the shop's own on/off switches, keyed the same way its manifest
117
+ * declares them. A site gating a component on a missing key reads undefined and
118
+ * the feature silently never renders, which is why it is always an object here.
119
+ */
120
+ export function normalizeSettings(raw) {
121
+ const src = raw || {};
122
+ return {
123
+ shopId: src.shop_id ?? null,
124
+ name: toString(src.store_name, 'Our shop'),
125
+ description: toString(src.description),
126
+ about: toString(src.about),
127
+ tagline: toString(src.tagline),
128
+ phone: toString(src.store_phone),
129
+ whatsapp: toString(src.whatsapp),
130
+ address: toString(src.store_address),
131
+ hours: src.business_hours ?? null,
132
+ currency: toString(src.currency_symbol, 'KSh'),
133
+ logo: src.logo_url || null,
134
+ website: toString(src.website_url),
135
+ colours: {
136
+ primary: src.primary_color || null,
137
+ secondary: src.secondary_color || null,
138
+ accent: src.accent_color || null,
139
+ nameAccent: src.name_accent || null,
140
+ },
141
+ featuredProductIds: toArray(src.featured_product_ids),
142
+ features: src.feature_toggles && typeof src.feature_toggles === 'object' ? src.feature_toggles : {},
143
+ social: {
144
+ instagram: toString(src.instagram),
145
+ facebook: toString(src.facebook),
146
+ tiktok: toString(src.tiktok),
147
+ },
148
+ };
149
+ }
150
+
151
+ /**
152
+ * GET /api/banners
153
+ * columns: id, type, title, subtitle, message, image_url, link_url, active,
154
+ * sort_order
155
+ *
156
+ * The route already filters to active rows and orders them, so both are carried
157
+ * through unchanged rather than re-derived.
158
+ */
159
+ export function normalizeBanner(raw = {}) {
160
+ return {
161
+ id: raw.id ?? null,
162
+ type: toString(raw.type, 'info'),
163
+ title: toString(raw.title),
164
+ subtitle: toString(raw.subtitle),
165
+ message: toString(raw.message),
166
+ image: raw.image_url || null,
167
+ link: raw.link_url || null,
168
+ active: raw.active !== false,
169
+ sortOrder: toNumber(raw.sort_order) ?? 0,
170
+ };
171
+ }
172
+
173
+ /**
174
+ * GET /api/page-content
175
+ * columns: id, page_key, section_key, content, created_at, updated_at
176
+ *
177
+ * `content` is the jsonb block the site renders; it is passed through untouched
178
+ * because its shape belongs to the site's own design, not to this package.
179
+ */
180
+ export function normalizePageContent(raw = {}) {
181
+ return {
182
+ id: raw.id ?? null,
183
+ pageKey: raw.page_key ?? null,
184
+ sectionKey: raw.section_key ?? null,
185
+ content: raw.content ?? null,
186
+ updatedAt: raw.updated_at || null,
187
+ };
188
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@framestudio/keel-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Read a Keel shop's catalogue, settings and content through a site token. One import, no database credential in the browser.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./client.js",
8
+ "module": "./client.js",
9
+ "exports": {
10
+ ".": "./client.js",
11
+ "./react": "./react.js"
12
+ },
13
+ "files": [
14
+ "client.js",
15
+ "normalize.js",
16
+ "react.js",
17
+ "README.md",
18
+ "CHANGELOG.md"
19
+ ],
20
+ "sideEffects": false,
21
+ "keywords": [
22
+ "keel",
23
+ "storefront",
24
+ "catalogue",
25
+ "minicatalogue",
26
+ "kenya"
27
+ ],
28
+ "scripts": {
29
+ "test": "node --test test/",
30
+ "build:embed": "node scripts/build-embed.mjs"
31
+ },
32
+ "dependencies": {
33
+ "@framestudio/keel-analytics": "^0.3.0"
34
+ },
35
+ "peerDependencies": {
36
+ "react": ">=18"
37
+ },
38
+ "peerDependenciesMeta": {
39
+ "react": {
40
+ "optional": true
41
+ }
42
+ },
43
+ "devDependencies": {
44
+ "esbuild": "^0.28.2",
45
+ "react": "^19.0.0",
46
+ "react-dom": "^19.0.0"
47
+ },
48
+ "engines": {
49
+ "node": ">=18"
50
+ }
51
+ }
package/react.js ADDED
@@ -0,0 +1,63 @@
1
+ import { createContext, createElement, useContext, useEffect, useState } from 'react'
2
+
3
+ /**
4
+ * React bindings. Optional, and deliberately thin.
5
+ *
6
+ * The core is plain async so a site without React pays nothing for this file.
7
+ * What lives here is the two things that are easy to get wrong: reading the
8
+ * client out of context, and not setting state after a component unmounts.
9
+ */
10
+ const KeelContext = createContext(null)
11
+
12
+ export function KeelProvider({ client, children }) {
13
+ return createElement(KeelContext.Provider, { value: client }, children)
14
+ }
15
+
16
+ export function useKeel() {
17
+ const client = useContext(KeelContext)
18
+ if (!client) {
19
+ throw new Error('useKeel must be used inside <KeelProvider client={...}>')
20
+ }
21
+ return client
22
+ }
23
+
24
+ /**
25
+ * Load one resource, with the three states a storefront actually renders:
26
+ * loading, data, and the error it must not swallow.
27
+ *
28
+ * `options` is compared by value (a serialised key), not by identity: a caller
29
+ * writing `usePageContent({ page: 'home' })` inline would otherwise create a new
30
+ * object every render and refetch forever.
31
+ */
32
+ export function useKeelResource(method, options) {
33
+ const client = useKeel()
34
+ const [state, setState] = useState({ data: null, error: null, loading: true })
35
+ const key = options === undefined ? '' : JSON.stringify(options)
36
+
37
+ useEffect(() => {
38
+ let cancelled = false
39
+ setState({ data: null, error: null, loading: true })
40
+
41
+ Promise.resolve()
42
+ .then(() => client[method](key ? JSON.parse(key) : undefined))
43
+ .then((data) => {
44
+ if (!cancelled) setState({ data, error: null, loading: false })
45
+ })
46
+ .catch((error) => {
47
+ if (!cancelled) setState({ data: null, error, loading: false })
48
+ })
49
+
50
+ return () => {
51
+ cancelled = true
52
+ }
53
+ }, [client, method, key])
54
+
55
+ return state
56
+ }
57
+
58
+ export const useProducts = () => useKeelResource('products')
59
+ export const useServices = () => useKeelResource('services')
60
+ export const useCatalogue = () => useKeelResource('catalogue')
61
+ export const useBanners = () => useKeelResource('banners')
62
+ export const useShopSettings = () => useKeelResource('settings')
63
+ export const usePageContent = (options) => useKeelResource('pageContent', options)