greatstore 0.0.0-stage → 0.2.3

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,296 @@
1
+ # `generateStructuredContent` deep dive
2
+
3
+ AI-generated, catalog-grounded JSON for UI you render yourself — the chat
4
+ panel is not involved.
5
+
6
+ ```js
7
+ const data = await window.GreatStore.generateStructuredContent(schema, prompt);
8
+ ```
9
+
10
+ - `schema` — a JSON Schema describing the output (or a Zod schema exposing
11
+ `.toJSONSchema()`).
12
+ - `prompt` — what to generate.
13
+ - Resolves to **the generated JSON object itself**, matching the schema.
14
+ Rejects with an `Error` on any failure.
15
+
16
+ Code samples here are framework-free reference implementations — re-express
17
+ them in the host repo's framework (React, Vue, Shopify Liquid, …) rather
18
+ than retrofitting them as-is.
19
+
20
+ ## The rules that make it work well
21
+
22
+ Each is unpacked in the sections below; this is the checklist.
23
+
24
+ 1. **Top level must be an object.** Want a list? Wrap it:
25
+ `{ type: "object", properties: { items: { type: "array", … } }, required: ["items"] }`.
26
+ 2. **Steer the whole output with the prompt, single fields with
27
+ `description`.** A property's `description` reaches the AI as guidance for
28
+ that field; it's optional, so use self-explanatory property names
29
+ (`benefitHeadline`, not `text1`) and describe only where the name isn't
30
+ enough.
31
+ 3. **Only `require` what's guaranteed.** `required` is strictly enforced; if
32
+ the catalog can't ground a required field the whole call can fail. Require
33
+ structural fields, keep per-product details (image URLs, prices) optional,
34
+ and make rendering tolerate missing values.
35
+ 4. **Point, don't paste.** GreatStore researches the store's live catalog on
36
+ its own — name the entity (`` `…the product "${productName}" (SKU ${sku})` ``)
37
+ and let it look the facts up. Don't fetch specs/prices/descriptions
38
+ yourself and paste them into the prompt. The one thing it *can't* see is
39
+ your page, so page-only context (which page the shopper is on, what the
40
+ section is for) does belong in the prompt.
41
+ 5. **Research is bounded by the store's connectors — validate before you
42
+ build.** The AI can only look up what the store's MCP connectors actually
43
+ provide. Ask for something outside them — currency conversion, live
44
+ shipping rates, review data the store never wired up — and it has nothing
45
+ to ground on, so it will decline, omit… or hallucinate. Before writing a
46
+ prompt or schema that depends on a data capability, run `npx greatstore connectors`
47
+ (and `npx greatstore connectors health`, [store-admin.md](store-admin.md)) and confirm
48
+ a connector for it exists; if it doesn't, don't ask for it.
49
+ 6. **Responses are cached** for up to ~24h per page + prompt + schema —
50
+ shared across anonymous visitors, per-shopper for identified ones. Keep
51
+ prompts deterministic per page — no timestamps, random values, or
52
+ per-visitor data (GreatStore already knows who the shopper is; see below).
53
+ 7. **Progressive enhancement, always.** Generate after the page renders into
54
+ a hidden container, reveal on success, leave the fallback on error. Render
55
+ generated strings via `textContent`, never `innerHTML`.
56
+ 8. **One rich call beats many small ones** — there's a per-visitor rate limit
57
+ (~20 requests/minute); fetch multiple surfaces with one combined schema.
58
+
59
+ ## What actually happens
60
+
61
+ 1. The SDK posts your schema + prompt to the store's GreatStore endpoint,
62
+ along with the current **page URL and page title** (sent automatically —
63
+ you don't pass them, and you can't override them).
64
+ 2. GreatStore first **researches**: it looks up real data from the store's
65
+ live catalog (products, prices, availability, store info) using read-only
66
+ lookups. The page URL/title serve as hints about which product or category
67
+ to look up — they are *not* treated as a source of product data, and the
68
+ page's DOM is never read. Research happens on GreatStore's side — your
69
+ prompt only needs to *point* it at the right SKU, product, or collection,
70
+ not carry the material. Its reach is exactly the store's MCP connectors:
71
+ validate with `npx greatstore connectors` ([store-admin.md](store-admin.md)) that a
72
+ connector for the data you want actually exists before you build on it —
73
+ research can't exceed the wired-up connectors, and prompts that assume
74
+ otherwise invite hallucinated filler.
75
+ 3. The AI then fills your schema from the researched data, under a strict
76
+ grounding contract: it must not invent product names, prices, images, IDs,
77
+ or descriptions. Fields it can't ground are omitted or `null`. For an
78
+ identified shopper this step also sees their shopper profile — the same
79
+ identity the chat assistant has — so the output can be subtly personalized
80
+ without you passing anything about the visitor.
81
+ 4. The output is validated against your schema (with internal retries) before
82
+ being returned and cached.
83
+
84
+ GreatStore already knows who's reading: identity rides the request the same
85
+ way it does for chat, and responses for identified shoppers are cached just
86
+ for them (anonymous visitors share one entry). The practical consequence:
87
+ never put shopper data in the prompt — it's redundant, and it poisons the
88
+ cache key.
89
+
90
+ ## Schema support
91
+
92
+ Top level **must describe an object**: `type: "object"` (or a bare
93
+ `properties` / `anyOf`). To get a list, wrap it in an object property.
94
+
95
+ Supported keywords (anything else is tolerated but ignored):
96
+
97
+ - Types: `object`, `array`, `string`, `number`, `integer`, `boolean`, `null`
98
+ - Structure: `properties`, `required`, `items`, `additionalProperties`
99
+ - Choice: `enum`, `const`, `anyOf`, `nullable`
100
+ - Constraints: `minimum`, `maximum`, `minLength`, `maxLength`, `minItems`,
101
+ `maxItems`, `pattern`, `format`, `default`
102
+ - Guidance: `description`, `example`, `title` (on any property)
103
+
104
+ Validation of the output is real: `required` is enforced, `enum`/`const`
105
+ must match, numeric and length bounds are checked, and
106
+ `additionalProperties: false` rejects extra keys. Constraints are therefore a
107
+ *tool* — `enum` reliably restricts a field — but every constraint is also a
108
+ way for generation to fail, so apply them only where you'd rather have no
109
+ content than non-conforming content.
110
+
111
+ Item counts are the exception. `minItems` is honored as the content is
112
+ written, so a list comes back with at least that many entries, and a list
113
+ longer than `maxItems` is cut to its first `maxItems` entries rather than
114
+ failing. The same applies to an app's `inputSchema`.
115
+
116
+ Zod schemas (or anything with a `.toJSONSchema()` method) are accepted and
117
+ converted automatically — `.describe("…")` becomes the field's `description`.
118
+
119
+ ### Field descriptions
120
+
121
+ A property's `description` is shown to the AI as guidance for that one
122
+ field, and an `example` shows the exact shape you want (`"4.5 out of 5"`,
123
+ `"SKU-1234"`). Both are optional: a field without them is filled from its
124
+ name, the prompt, and its constraints.
125
+
126
+ ```js
127
+ {
128
+ type: "object",
129
+ properties: {
130
+ headline: { type: "string", maxLength: 60 },
131
+ priceJustification: {
132
+ type: "string",
133
+ description: "One sentence on why the price is fair, citing a real material or feature",
134
+ },
135
+ rating: { type: "string", example: "4.5 out of 5" },
136
+ },
137
+ required: ["headline"],
138
+ }
139
+ ```
140
+
141
+ Split the work between the two channels:
142
+
143
+ - **Prompt** — the situation, the task as a whole, grounding, and voice.
144
+ - **`description` / `example`** — what one specific field holds: its unit, length in
145
+ words, perspective ("first-person, as the shopper"), or how it relates to
146
+ a sibling. Instructions that apply to the whole output don't belong here.
147
+ - Property *names* still carry most of the intent — make them
148
+ self-documenting (`ctaLabel`, `warmthRating`, `priceJustification`) and
149
+ reach for a description when the name can't say it.
150
+
151
+ ## Prompting guide
152
+
153
+ The prompt carries the instructions for the output as a whole (per-field
154
+ guidance can sit in each field's `description` or `example`). A good prompt states, in
155
+ order:
156
+
157
+ 1. **Context** — what page/situation the shopper is in, naming the entity so
158
+ research targets the right thing (the AI can't see your DOM, so identify
159
+ it explicitly):
160
+ `The shopper is viewing the product "Aurora Down Parka" (SKU AUR-021) on its product page.`
161
+ 2. **Task** — what to generate, mapped loosely onto your schema's fields:
162
+ `Write a heading and 3 reasons to love it; each reason has a short title and one supporting sentence.`
163
+ 3. **Grounding expectations** — what store data to draw on:
164
+ `Base every claim on the product's real materials, features, and price.`
165
+ 4. **Voice** — tone and constraints:
166
+ `Warm and concrete. No exclamation marks, no generic marketing filler.`
167
+
168
+ Note what's *not* in that prompt: no pasted specs, prices, or descriptions.
169
+ Pointing at the SKU is enough — GreatStore researches the rest itself, from
170
+ data that's live rather than whatever was true when you wrote the prompt.
171
+
172
+ Anti-patterns:
173
+
174
+ - **Pasting researched material into the prompt** (specs, prices,
175
+ descriptions you fetched from your platform's API). GreatStore researches
176
+ the live catalog itself — point it at the SKU/product/collection and let
177
+ it look things up. Pasted facts go stale, bloat the cache key, and compete
178
+ with the fresher data research returns.
179
+ - **Per-visitor or per-moment data in the prompt** (names, cart contents,
180
+ timestamps, `Math.random()`): destroys caching, so every visitor pays full
181
+ generation latency and the store pays for every call — and it's redundant,
182
+ because GreatStore already knows the shopper and personalizes for
183
+ identified ones server-side. If you need per-shopper *interaction*, that's
184
+ what `sendMessage` and the chat panel are for.
185
+ - **Asking for data no connector provides** ("convert the price to EUR",
186
+ "estimate delivery to the shopper's city"): research can't exceed the
187
+ store's MCP connectors, and the AI may hallucinate plausible-looking
188
+ values rather than leave the field empty. Validate first — `npx greatstore connectors`
189
+ shows what's wired up ([store-admin.md](store-admin.md)); if there's no
190
+ connector for it, don't ask for it.
191
+ - **Asking it to read the page** ("summarize the reviews shown below") — it
192
+ can't. Page-only data (review snippets, UGC, things that exist nowhere but
193
+ the DOM) is the one kind worth inlining — keep it stable per page so
194
+ caching still works.
195
+ - **Asking for minute-fresh operational data** (exact live stock counts,
196
+ delivery countdowns). Even when a connector could answer, responses cache
197
+ for up to ~24h — display operational data from your own platform APIs and
198
+ use GreatStore for *editorial intelligence over the catalog*.
199
+ - **Putting whole-output instructions in a field's `description`** (voice,
200
+ grounding, what the page is) — they belong in the prompt, where they apply
201
+ to every field.
202
+
203
+ ## Caching: design for it
204
+
205
+ Responses are cached server-side for up to **24 hours**, keyed by the
206
+ combination of page URL + page title + prompt + schema. Anonymous visitors
207
+ share one entry per key; identified shoppers each get their own (their
208
+ output may be personalized, so it's only ever served back to them).
209
+ (Tracking query params like `utm_*`/`gclid` and the URL fragment are
210
+ ignored, so ad-tagged visits share the campaign-free page's cache entry.
211
+ Meaningful params like `?product=123` are part of the key.)
212
+
213
+ Practical consequences:
214
+
215
+ - **The first render pays, repeats fly.** Expect a few seconds on a cache
216
+ miss and near-instant responses after — shared across all anonymous
217
+ traffic, per-shopper for identified traffic (the research underneath is
218
+ cached briefly and shared, so even those misses are cheaper than cold).
219
+ Design loading states for the miss case.
220
+ - **Same call on different pages = different content**, automatically — the
221
+ page URL is in the key and in the AI's hints. A single site-wide snippet
222
+ with a constant prompt yields per-page content for free.
223
+ - **Content refreshes roughly daily.** Don't build experiences that assume
224
+ minute-level freshness.
225
+ - **To force different content, change the prompt or schema** (e.g. a
226
+ campaign variant string that changes weekly — deliberate, low-cardinality
227
+ variation is fine; per-visitor cardinality is not).
228
+
229
+ The catalog research underneath is also cached briefly, so several distinct
230
+ surfaces on the same page (different prompts/schemas) stay cheap even on
231
+ cold cache.
232
+
233
+ ## Errors and how to handle them
234
+
235
+ The promise rejects with `new Error(message)`. The message is
236
+ developer-facing — never render it to shoppers. Server-side failures also
237
+ carry `error.code`, and a decline carries `error.reason`. Cases:
238
+
239
+ | Case | Message you'll see | Retry? |
240
+ |---|---|---|
241
+ | Bad input (empty prompt, non-object schema) | thrown immediately by the SDK | Fix the call |
242
+ | Invalid schema shape | `Invalid schema: …` | Fix the schema |
243
+ | AI declined the request | `The assistant declined to generate content for this request.` with `error.reason` (below) | No — permanent for that prompt/schema. Rework the prompt. |
244
+ | Output couldn't satisfy the schema | `Failed to produce valid structured content` | No — usually `required`/constraints demand data the catalog lacks. Loosen the schema. |
245
+ | Rate limit (~20/min per visitor) | rate-limit message | Later — and consolidate calls |
246
+ | Network / server | varies | Next page load |
247
+
248
+ A decline is only ever one of these `error.reason` values — anything else
249
+ (vague wording, missing data for optional fields, marketing copy) is served:
250
+
251
+ | `reason` | Declined because the request… |
252
+ |---|---|
253
+ | `off_topic` | has nothing to do with the store or shopping there (homework, code, news, another business's products) |
254
+ | `harmful` | asks for unsafe, hateful, sexual, or illegal content, or advice that could hurt someone |
255
+ | `deceptive` | asks for fake reviews, invented discounts or scarcity, claims the catalog contradicts, or impersonating/disparaging a named brand or person |
256
+ | `system_probe` | asks about or tries to override the assistant's own instructions or tools |
257
+
258
+ The uniform shopper-facing strategy: render into a hidden-by-default
259
+ container, reveal on success, leave hidden (or show your static fallback) on
260
+ any rejection. One `try/catch`, no case analysis needed unless you're
261
+ logging.
262
+
263
+ ## Performance pattern
264
+
265
+ Fire generation as early as possible without blocking render — top of your
266
+ deferred script, before other work:
267
+
268
+ ```js
269
+ const highlightsPromise = window.GreatStore?.generateStructuredContent
270
+ ? window.GreatStore.generateStructuredContent(schema, prompt).catch(() => null)
271
+ : Promise.resolve(null);
272
+
273
+ // …rest of page setup…
274
+
275
+ const data = await highlightsPromise;
276
+ if (data) renderHighlights(data);
277
+ ```
278
+
279
+ The `.catch(() => null)` attached immediately avoids unhandled-rejection
280
+ noise while keeping a single render path.
281
+
282
+ For multiple surfaces on one page, prefer **one call with a combined
283
+ schema** over parallel calls — it's one research pass, one cache entry, and
284
+ no rate-limit pressure:
285
+
286
+ ```js
287
+ const schema = {
288
+ type: "object",
289
+ properties: {
290
+ highlights: { /* … */ },
291
+ faq: { /* … */ },
292
+ crossSell: { /* … */ },
293
+ },
294
+ required: ["highlights"],
295
+ };
296
+ ```
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "greatstore",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.3",
4
+ "description": "CLI for administering GreatStore stores and authoring custom components.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "files": [
8
+ "dist",
9
+ "README.md",
10
+ "CHANGELOG.md"
11
+ ],
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
15
+ "scripts": {
16
+ "build": "tsup",
17
+ "dev": "tsup --watch",
18
+ "typecheck": "tsc --noEmit",
19
+ "test": "vitest run",
20
+ "test:watch": "vitest"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^20.14.0",
24
+ "tsup": "^8.3.0",
25
+ "typescript": "^5.8.2",
26
+ "vitest": "^2.1.0"
27
+ },
28
+ "bin": {
29
+ "greatstore": "./dist/cli.js"
30
+ }
31
+ }