@luma-ai/react 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/dist/server.js ADDED
@@ -0,0 +1,277 @@
1
+ import { z } from "zod";
2
+ //#region ../assistant-contract/src/site.ts
3
+ var siteToolNames = [
4
+ "siteInfo",
5
+ "searchSite",
6
+ "searchProducts",
7
+ "getProduct",
8
+ "inspectPage",
9
+ "showGuide",
10
+ "navigate",
11
+ "runAction"
12
+ ];
13
+ var text = z.string().trim().max(300);
14
+ var guideStep = z.object({
15
+ targetId: text.min(1),
16
+ title: text.min(1),
17
+ description: z.string().trim().min(1).max(1200),
18
+ completion: z.enum([
19
+ "next",
20
+ "click",
21
+ "change",
22
+ "expanded"
23
+ ]),
24
+ expectedTargetId: text.nullable().optional().describe("Another observed element to verify, or null when no additional target is needed.")
25
+ });
26
+ z.object({}), z.object({
27
+ query: text,
28
+ page: z.number().int().min(1).max(1e3).default(1)
29
+ }), z.object({
30
+ query: text,
31
+ minPrice: z.number().nonnegative().nullable().optional().describe("Minimum price in store currency, or null when no minimum was requested."),
32
+ maxPrice: z.number().nonnegative().nullable().optional().describe("Maximum price in store currency, or null when no budget was requested. Zero means free products only."),
33
+ category: text.nullable().optional().describe("Known category slug, or null for all categories."),
34
+ inStock: z.boolean().default(true),
35
+ page: z.number().int().min(1).max(1e3).default(1)
36
+ }), z.object({ productId: z.union([z.number().int().positive(), text.min(1)]) }), z.object({ query: text.default("") }), z.object({
37
+ destinationId: text.min(1),
38
+ explanation: z.string().trim().min(1).max(600)
39
+ }), z.object({
40
+ action: text.min(1),
41
+ input: z.record(z.string(), z.unknown()),
42
+ explanation: z.string().trim().min(1).max(600)
43
+ });
44
+ var siteActionNamePattern = /^[A-Za-z][\w-]{0,63}$/;
45
+ var siteActionSchema = z.object({
46
+ name: z.string().regex(siteActionNamePattern),
47
+ description: z.string().trim().min(1).max(500),
48
+ input: z.record(z.string(), z.unknown()).refine((value) => JSON.stringify(value).length <= 4e3, "Schema too large"),
49
+ confirm: z.boolean()
50
+ });
51
+ var pageElementSchema = z.object({
52
+ id: text,
53
+ label: text,
54
+ role: text,
55
+ href: z.string().max(2048).optional(),
56
+ expanded: z.boolean().optional(),
57
+ options: z.array(text).max(30).optional()
58
+ });
59
+ z.object({
60
+ url: z.string().max(2048),
61
+ title: text,
62
+ revision: text,
63
+ elements: z.array(pageElementSchema).max(100),
64
+ restricted: z.boolean().optional(),
65
+ appContext: z.record(z.string(), z.unknown()).optional()
66
+ });
67
+ z.object({ steps: z.array(guideStep).min(1).max(8).describe("Ordered steps shown in sequence on the current page without returning to you between them.") });
68
+ var siteFeatures = ["guideTour"];
69
+ var SITE_CONTEXT_MAX_LENGTH = 24e3;
70
+ var siteContextSchema = z.object({
71
+ version: z.literal(1),
72
+ origin: z.url().max(2048),
73
+ capabilities: z.array(z.enum(siteToolNames)).max(12),
74
+ features: z.array(z.enum(siteFeatures)).max(8).optional(),
75
+ actions: z.array(siteActionSchema).max(20).optional()
76
+ }).refine((value) => JSON.stringify(value).length <= SITE_CONTEXT_MAX_LENGTH, "Site context too large").refine((value) => new Set(value.actions?.map((action) => action.name)).size === (value.actions?.length ?? 0), "Duplicate action names");
77
+ var siteToolOutputSchema = z.object({
78
+ status: z.enum([
79
+ "ok",
80
+ "completed",
81
+ "cancelled",
82
+ "unavailable",
83
+ "navigated",
84
+ "error"
85
+ ]),
86
+ data: z.unknown().optional(),
87
+ message: z.string().max(1200).optional()
88
+ }).refine((value) => JSON.stringify(value).length <= 48e3, "Tool output too large");
89
+ z.object({
90
+ messageId: z.string().max(100),
91
+ results: z.array(z.object({
92
+ toolCallId: z.string().max(200),
93
+ output: siteToolOutputSchema
94
+ })).min(1).max(8)
95
+ });
96
+ //#endregion
97
+ //#region src/core/actions.ts
98
+ /**
99
+ * Define an action once and share it between the server handler (which declares it to the
100
+ * assistant) and the page component that runs it with useLumaAction.
101
+ */
102
+ function defineAction(definition) {
103
+ if (!siteActionNamePattern.test(definition.name)) throw new Error(`Invalid Luma action name "${definition.name}". Use letters, digits, "_" or "-", starting with a letter.`);
104
+ return {
105
+ ...definition,
106
+ confirm: definition.confirm ?? true
107
+ };
108
+ }
109
+ /** The serializable declaration the assistant receives. */
110
+ function actionContract(definition) {
111
+ const { $schema: _, ...input } = z.toJSONSchema(definition.input, { unrepresentable: "any" });
112
+ return siteActionSchema.parse({
113
+ name: definition.name,
114
+ description: definition.description,
115
+ input,
116
+ confirm: definition.confirm
117
+ });
118
+ }
119
+ //#endregion
120
+ //#region src/core/config.ts
121
+ var API_BASE_URLS = {
122
+ internal: "https://ir.lumai.ir/api",
123
+ direct: "https://dash.lumai.ir/api"
124
+ };
125
+ //#endregion
126
+ //#region src/server.ts
127
+ var defaultCapabilities = [
128
+ "siteInfo",
129
+ "searchSite",
130
+ "navigate",
131
+ "inspectPage",
132
+ "showGuide"
133
+ ];
134
+ var firstPartyHosts = ["dash.lumai.ir", "ir.lumai.ir"];
135
+ function json(body, status = 200, headers = {}) {
136
+ return new Response(JSON.stringify(body), {
137
+ status,
138
+ headers: {
139
+ "Content-Type": "application/json",
140
+ "Cache-Control": "no-store, private, max-age=0",
141
+ ...headers
142
+ }
143
+ });
144
+ }
145
+ var docs = "https://dash.lumai.ir/docs/react/troubleshooting";
146
+ /** Error response with a stable code; the docs explain each one. */
147
+ function fail(status, code, error, headers) {
148
+ return json({
149
+ error,
150
+ code
151
+ }, status, headers);
152
+ }
153
+ /** Server-side detail for the site owner; never sent to the browser. */
154
+ function log(code, message) {
155
+ console.error(`[@luma-ai/react] ${code}: ${message} See ${docs}#${code.toLowerCase()}`);
156
+ }
157
+ var upstreamHints = {
158
+ 400: "Luma rejected the site context (for example, actions larger than the limits).",
159
+ 401: "The API key is invalid or revoked. Create one at https://dash.lumai.ir/developers/api/keys.",
160
+ 404: "The assistant was not found for this API key. Check assistantId and that the key belongs to the assistant's account.",
161
+ 429: "Luma API rate limit reached."
162
+ };
163
+ function first(value) {
164
+ return value?.split(",")[0]?.trim() || null;
165
+ }
166
+ /** The site origin this request belongs to, or null for a foreign browser origin. */
167
+ function siteOrigin(request, siteUrl) {
168
+ const origin = request.headers.get("origin");
169
+ try {
170
+ if (siteUrl) {
171
+ const site = new URL(siteUrl).origin;
172
+ return origin && origin !== site ? null : site;
173
+ }
174
+ const url = new URL(request.url);
175
+ const host = first(request.headers.get("x-forwarded-host")) ?? request.headers.get("host") ?? url.host;
176
+ if (origin) {
177
+ const parsed = new URL(origin);
178
+ return parsed.host === host ? parsed.origin : null;
179
+ }
180
+ const protocol = first(request.headers.get("x-forwarded-proto")) ?? url.protocol.slice(0, -1);
181
+ return new URL(`${protocol}://${host}`).origin;
182
+ } catch {
183
+ return null;
184
+ }
185
+ }
186
+ /**
187
+ * Creates the POST handler that starts visitor sessions for LumaProvider's sessionEndpoint.
188
+ * It uses the Fetch API, so it works as a Next.js route handler, a TanStack Start server
189
+ * route, a React Router action, or in any runtime with Request/Response.
190
+ */
191
+ function createLumaSessionHandler(options) {
192
+ const apiBaseUrl = (options.apiBaseUrl ?? API_BASE_URLS[options.server ?? "internal"]).replace(/\/+$/, "");
193
+ const browserApiBaseUrl = (options.browserApiBaseUrl ?? apiBaseUrl).replace(/\/+$/, "");
194
+ const allowed = new Set(options.capabilities ?? siteToolNames);
195
+ return async function handleLumaSession(request) {
196
+ if (request.method !== "POST") return fail(405, "LUMA_METHOD_NOT_ALLOWED", "Method not allowed", { Allow: "POST" });
197
+ if (!options.apiKey || !options.assistantId) {
198
+ log("LUMA_NOT_CONFIGURED", `createLumaSessionHandler needs apiKey and assistantId (missing: ${[!options.apiKey && "apiKey", !options.assistantId && "assistantId"].filter(Boolean).join(", ")}). Set LUMA_API_KEY and LUMA_ASSISTANT_ID on the server.`);
199
+ return fail(503, "LUMA_NOT_CONFIGURED", "Assistant unavailable");
200
+ }
201
+ const origin = siteOrigin(request, options.siteUrl);
202
+ if (!origin || request.headers.get("sec-fetch-site") === "cross-site") return fail(403, "LUMA_ORIGIN_NOT_ALLOWED", "Origin not allowed");
203
+ const verdict = await options.authorize?.(request);
204
+ if (verdict instanceof Response) return verdict;
205
+ if (verdict === false) return fail(403, "LUMA_FORBIDDEN", "Forbidden");
206
+ const text = await request.text();
207
+ if (text.length > 16e3) return fail(413, "LUMA_INVALID_REQUEST", "Request too large");
208
+ let body;
209
+ try {
210
+ body = text ? JSON.parse(text) : {};
211
+ } catch {
212
+ return fail(400, "LUMA_INVALID_REQUEST", "Invalid request");
213
+ }
214
+ const requested = Array.isArray(body?.capabilities) ? body.capabilities.filter((name) => siteToolNames.includes(name)) : defaultCapabilities;
215
+ const actions = (options.actions ?? []).map(actionContract);
216
+ const capabilities = [...new Set(requested)].filter((name) => allowed.has(name) && (name !== "runAction" || actions.length));
217
+ const parsed = siteContextSchema.safeParse({
218
+ version: 1,
219
+ origin,
220
+ capabilities,
221
+ ...capabilities.includes("showGuide") ? { features: ["guideTour"] } : {},
222
+ ...capabilities.includes("runAction") ? { actions } : {}
223
+ });
224
+ if (!parsed.success) {
225
+ log("LUMA_INVALID_SITE_CONTEXT", `The site context is invalid: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "context"}: ${issue.message}`).join("; ")}. Check the actions passed to createLumaSessionHandler (at most 20, schemas up to 4000 characters).`);
226
+ return fail(500, "LUMA_INVALID_SITE_CONTEXT", "Assistant unavailable");
227
+ }
228
+ const site = parsed.data;
229
+ const resume = request.headers.get("x-session-id");
230
+ let response;
231
+ try {
232
+ response = await (options.fetch ?? fetch)(`${apiBaseUrl}/assistant/${encodeURIComponent(options.assistantId)}/session`, {
233
+ method: "POST",
234
+ headers: {
235
+ "Content-Type": "application/json",
236
+ Accept: "application/json",
237
+ "x-api-key": options.apiKey
238
+ },
239
+ body: JSON.stringify({
240
+ site,
241
+ ...resume && /^[A-Za-z0-9_-]{16,200}$/.test(resume) ? { sessionId: resume } : {}
242
+ }),
243
+ redirect: "manual",
244
+ cache: "no-store",
245
+ signal: AbortSignal.timeout(15e3)
246
+ });
247
+ } catch (error) {
248
+ log("LUMA_UPSTREAM_UNREACHABLE", `Could not reach ${apiBaseUrl} (${error instanceof Error ? error.message : "network error"}). Try server: "${options.server === "direct" ? "internal" : "direct"}" if this host cannot reach it.`);
249
+ return fail(502, "LUMA_UPSTREAM_UNREACHABLE", "Unable to create session");
250
+ }
251
+ if (!response.ok) {
252
+ log("LUMA_UPSTREAM_REJECTED", `Luma returned HTTP ${response.status}. ${upstreamHints[response.status] ?? ""}`.trim());
253
+ return fail(502, "LUMA_UPSTREAM_REJECTED", "Unable to create session");
254
+ }
255
+ const payload = await response.json().catch(() => null);
256
+ const data = payload?.data;
257
+ if (payload?.success !== true || !data || typeof data.sessionId !== "string" || !data.sessionId.trim()) {
258
+ log("LUMA_UPSTREAM_REJECTED", "Luma returned an unexpected session response.");
259
+ return fail(502, "LUMA_UPSTREAM_REJECTED", "Unable to create session");
260
+ }
261
+ let avatar = typeof data.avatar === "string" && /^https?:\/\//.test(data.avatar) ? data.avatar : null;
262
+ if (avatar && /^https?:\/\//.test(browserApiBaseUrl) && firstPartyHosts.includes(new URL(avatar).host)) avatar = avatar.replace(/^https?:\/\/[^/]+/, browserApiBaseUrl.replace(/\/api$/, ""));
263
+ return json({
264
+ assistantId: options.assistantId,
265
+ sessionId: data.sessionId,
266
+ name: typeof data.name === "string" ? data.name : "",
267
+ color: typeof data.color === "string" ? data.color : "blue",
268
+ avatar,
269
+ siteContext: site,
270
+ chatEndpoint: `${browserApiBaseUrl}/assistant/chat/widget`
271
+ });
272
+ };
273
+ }
274
+ //#endregion
275
+ export { createLumaSessionHandler, defineAction };
276
+
277
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","names":[],"sources":["../../assistant-contract/src/site.ts","../src/core/actions.ts","../src/core/config.ts","../src/server.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport const siteToolNames = [\n \"siteInfo\",\n \"searchSite\",\n \"searchProducts\",\n \"getProduct\",\n \"inspectPage\",\n \"showGuide\",\n \"navigate\",\n \"runAction\",\n] as const;\nexport type SiteToolName = (typeof siteToolNames)[number];\nconst text = z.string().trim().max(300);\nconst guideStep = z.object({\n targetId: text.min(1),\n title: text.min(1),\n description: z.string().trim().min(1).max(1200),\n completion: z.enum([\"next\", \"click\", \"change\", \"expanded\"]),\n expectedTargetId: text\n .nullable()\n .optional()\n .describe(\n \"Another observed element to verify, or null when no additional target is needed.\",\n ),\n});\nexport const siteToolInputs = {\n siteInfo: z.object({}),\n searchSite: z.object({\n query: text,\n page: z.number().int().min(1).max(1000).default(1),\n }),\n searchProducts: z.object({\n query: text,\n minPrice: z\n .number()\n .nonnegative()\n .nullable()\n .optional()\n .describe(\n \"Minimum price in store currency, or null when no minimum was requested.\",\n ),\n maxPrice: z\n .number()\n .nonnegative()\n .nullable()\n .optional()\n .describe(\n \"Maximum price in store currency, or null when no budget was requested. Zero means free products only.\",\n ),\n category: text\n .nullable()\n .optional()\n .describe(\"Known category slug, or null for all categories.\"),\n inStock: z.boolean().default(true),\n page: z.number().int().min(1).max(1000).default(1),\n }),\n getProduct: z.object({\n productId: z.union([z.number().int().positive(), text.min(1)]),\n }),\n inspectPage: z.object({ query: text.default(\"\") }),\n showGuide: guideStep,\n navigate: z.object({\n destinationId: text.min(1),\n explanation: z.string().trim().min(1).max(600),\n }),\n runAction: z.object({\n action: text.min(1),\n input: z.record(z.string(), z.unknown()),\n explanation: z.string().trim().min(1).max(600),\n }),\n};\nexport const siteActionNamePattern = /^[A-Za-z][\\w-]{0,63}$/;\nexport const siteActionSchema = z.object({\n name: z.string().regex(siteActionNamePattern),\n description: z.string().trim().min(1).max(500),\n // JSON Schema for the action input, validated again by the executing page.\n input: z\n .record(z.string(), z.unknown())\n .refine((value) => JSON.stringify(value).length <= 4000, \"Schema too large\"),\n confirm: z.boolean(),\n});\nexport type SiteAction = z.infer<typeof siteActionSchema>;\nexport const pageElementSchema = z.object({\n id: text,\n label: text,\n role: text,\n href: z.string().max(2048).optional(),\n expanded: z.boolean().optional(),\n options: z.array(text).max(30).optional(),\n});\nexport const pageSnapshotSchema = z.object({\n url: z.string().max(2048),\n title: text,\n revision: text,\n elements: z.array(pageElementSchema).max(100),\n restricted: z.boolean().optional(),\n // Structured state the website shares deliberately (React useLumaContext).\n appContext: z.record(z.string(), z.unknown()).optional(),\n});\nexport type PageSnapshot = z.infer<typeof pageSnapshotSchema>;\nexport type GuideInput = z.infer<typeof guideStep>;\n/** showGuide input for sites announcing the guideTour feature. */\nexport const guideTourInput = z.object({\n steps: z\n .array(guideStep)\n .min(1)\n .max(8)\n .describe(\n \"Ordered steps shown in sequence on the current page without returning to you between them.\",\n ),\n});\n/** Accepts tour input and the single-step input of older servers. */\nexport function guideSteps(input: unknown): GuideInput[] | null {\n const tour = guideTourInput.safeParse(input);\n if (tour.success) return tour.data.steps;\n const step = guideStep.safeParse(input);\n return step.success ? [step.data] : null;\n}\nexport const siteFeatures = [\"guideTour\"] as const;\nexport const SITE_CONTEXT_MAX_LENGTH = 24000;\nexport const siteContextSchema = z\n .object({\n version: z.literal(1),\n origin: z.url().max(2048),\n capabilities: z.array(z.enum(siteToolNames)).max(12),\n // Optional so older plugins and servers interoperate in both directions.\n features: z.array(z.enum(siteFeatures)).max(8).optional(),\n actions: z.array(siteActionSchema).max(20).optional(),\n })\n .refine(\n (value) => JSON.stringify(value).length <= SITE_CONTEXT_MAX_LENGTH,\n \"Site context too large\",\n )\n .refine(\n (value) =>\n new Set(value.actions?.map((action) => action.name)).size ===\n (value.actions?.length ?? 0),\n \"Duplicate action names\",\n );\nexport type SiteContext = z.infer<typeof siteContextSchema>;\nexport const siteToolOutputSchema = z\n .object({\n status: z.enum([\n \"ok\",\n \"completed\",\n \"cancelled\",\n \"unavailable\",\n \"navigated\",\n \"error\",\n ]),\n data: z.unknown().optional(),\n message: z.string().max(1200).optional(),\n })\n .refine(\n (value) => JSON.stringify(value).length <= 48000,\n \"Tool output too large\",\n );\nexport type SiteToolOutput = z.infer<typeof siteToolOutputSchema>;\nexport type SiteDestination = {\n id: string;\n title: string;\n url: string;\n description?: string;\n};\nexport type SiteProduct = SiteDestination & {\n productId: number | string;\n image: string | null;\n price: string;\n currency: string;\n inStock: boolean;\n type: string;\n attributes: Record<string, string[]>;\n variations?: Array<{\n id: number | string;\n attributes: Record<string, string>;\n price: string;\n inStock: boolean;\n }>;\n};\nexport const siteContinuationSchema = z.object({\n messageId: z.string().max(100),\n results: z\n .array(\n z.object({\n toolCallId: z.string().max(200),\n output: siteToolOutputSchema,\n }),\n )\n .min(1)\n .max(8),\n});\nexport type SiteContinuation = z.infer<typeof siteContinuationSchema>;\n","import { z } from \"zod\";\nimport {\n siteActionNamePattern,\n siteActionSchema,\n type SiteAction,\n} from \"@luma/assistant-contract/site\";\n\n/** An app action the assistant may propose, such as adding a product to the cart. */\nexport type LumaActionDefinition<Input = unknown> = {\n name: string;\n /** Tells the model when to use the action. */\n description: string;\n /** Short Persian label shown to the visitor, e.g. \"افزودن به سبد خرید\". */\n title?: string;\n /** When true (default) the visitor approves every run. */\n confirm: boolean;\n input: z.ZodType<Input>;\n};\n\n/**\n * Define an action once and share it between the server handler (which declares it to the\n * assistant) and the page component that runs it with useLumaAction.\n */\nexport function defineAction<Schema extends z.ZodType>(definition: {\n name: string;\n description: string;\n title?: string;\n confirm?: boolean;\n input: Schema;\n}): LumaActionDefinition<z.output<Schema>> {\n if (!siteActionNamePattern.test(definition.name))\n throw new Error(\n `Invalid Luma action name \"${definition.name}\". Use letters, digits, \"_\" or \"-\", starting with a letter.`,\n );\n return {\n ...definition,\n confirm: definition.confirm ?? true,\n } as LumaActionDefinition<z.output<Schema>>;\n}\n\n/** The serializable declaration the assistant receives. */\nexport function actionContract(definition: LumaActionDefinition): SiteAction {\n const { $schema: _, ...input } = z.toJSONSchema(definition.input, {\n unrepresentable: \"any\",\n }) as Record<string, unknown>;\n return siteActionSchema.parse({\n name: definition.name,\n description: definition.description,\n input,\n confirm: definition.confirm,\n });\n}\n","import {\n siteContextSchema,\n type SiteContext,\n} from \"@luma/assistant-contract/site\";\nimport type { AssistantSessionData } from \"@luma/assistant-contract/protocol\";\n\nexport type ChatPosition = \"bottom-left\" | \"bottom-right\";\nexport type ChatSize = \"sm\" | \"md\" | \"lg\" | \"xl\";\nexport type IconSize = \"sm\" | \"md\" | \"lg\" | \"xl\";\n\n/** Visual options shared by the WordPress plugin settings and LumaProvider props. */\nexport type LumaAppearance = {\n position?: ChatPosition;\n size?: ChatSize;\n /** Overrides the assistant name from the dashboard. */\n title?: string;\n subtitle?: string;\n placeholder?: string;\n paddingBottom?: number;\n paddingSide?: number;\n iconSize?: IconSize;\n mobileEnabled?: boolean;\n mobileSize?: ChatSize | \"full\";\n mobilePaddingBottom?: number;\n mobilePaddingSide?: number;\n mobileIconSize?: IconSize;\n};\n\nexport const API_BASE_URLS = {\n internal: \"https://ir.lumai.ir/api\",\n direct: \"https://dash.lumai.ir/api\",\n} as const;\nexport type LumaServer = keyof typeof API_BASE_URLS;\n\n/** How the browser obtains a visitor session. */\nexport type Connection = {\n /** server: your backend (or the WordPress plugin) holds the API key. public: keyless allowed-domain session. */\n mode: \"server\" | \"public\";\n sessionEndpoint?: string;\n assistantId?: string;\n chatEndpoint?: string;\n apiBaseUrl: string;\n /** Site context fixed by the host (WordPress), instead of one negotiated per session. */\n siteContext?: SiteContext;\n /** Conversation storage namespace; one conversation per scope and tab. */\n scope: string;\n};\n\nexport type SessionData = Omit<AssistantSessionData, \"avatar\"> & {\n avatar?: string;\n assistantId?: string;\n chatEndpoint?: string;\n siteContext?: SiteContext;\n};\n/** A session with everything the chat needs, after applying connection defaults. */\nexport type ResolvedSession = SessionData & {\n assistantId: string;\n chatEndpoint: string;\n};\n\nexport function parseSession(value: unknown): SessionData {\n // The Luma API wraps the session in { success, data }; proxies return it directly.\n const raw =\n value && typeof value === \"object\" && \"data\" in value && !(\"sessionId\" in value)\n ? (value as { data: unknown }).data\n : value;\n if (\n !raw ||\n typeof raw !== \"object\" ||\n !(\"sessionId\" in raw) ||\n typeof raw.sessionId !== \"string\" ||\n !raw.sessionId.trim()\n ) {\n throw new Error(\"Invalid session response\");\n }\n const data = raw as Record<string, unknown>;\n const site = siteContextSchema.safeParse(data.siteContext);\n return {\n sessionId: raw.sessionId,\n name: typeof data.name === \"string\" ? data.name : \"دستیار هوشمند\",\n color: typeof data.color === \"string\" ? data.color : \"blue\",\n avatar:\n typeof data.avatar === \"string\" && /^https?:\\/\\//.test(data.avatar)\n ? data.avatar\n : undefined,\n ...(typeof data.assistantId === \"string\"\n ? { assistantId: data.assistantId }\n : {}),\n ...(typeof data.chatEndpoint === \"string\" &&\n /^(https?:\\/\\/|\\/)/.test(data.chatEndpoint)\n ? { chatEndpoint: data.chatEndpoint }\n : {}),\n ...(site.success ? { siteContext: site.data } : {}),\n };\n}\n","import {\n siteContextSchema,\n siteToolNames,\n type SiteToolName,\n} from \"@luma/assistant-contract/site\";\nimport { actionContract, type LumaActionDefinition } from \"./core/actions\";\nimport { API_BASE_URLS, type LumaServer } from \"./core/config\";\n\nexport { defineAction, type LumaActionDefinition } from \"./core/actions\";\n\nexport type LumaSessionHandlerOptions = {\n /** Luma API key. Keep it in a server-only environment variable. */\n apiKey: string;\n assistantId: string;\n /** Luma API host: \"internal\" (ir.lumai.ir, default) or \"direct\" (dash.lumai.ir). */\n server?: LumaServer;\n /** Overrides the API base URL this server calls, e.g. for local development. */\n apiBaseUrl?: string;\n /** API base URL visitors' browsers use for chat, when it differs from apiBaseUrl. */\n browserApiBaseUrl?: string;\n /** Public site URL. Defaults to the request's host; set it behind proxies that rewrite Host. */\n siteUrl?: string;\n /** Owner allowlist of assistant tools. Defaults to all; the page requests what it can run. */\n capabilities?: SiteToolName[];\n /** Actions the assistant may propose; pages run them with useLumaAction. */\n actions?: LumaActionDefinition[];\n /**\n * Your own visitor check or rate limit. Return false (403) or a Response to reject.\n * Sessions spend this assistant's credits, so limit them per visitor in production.\n */\n authorize?: (\n request: Request,\n ) => boolean | Response | Promise<boolean | Response>;\n fetch?: typeof fetch;\n};\n\nconst defaultCapabilities: SiteToolName[] = [\n \"siteInfo\",\n \"searchSite\",\n \"navigate\",\n \"inspectPage\",\n \"showGuide\",\n];\nconst firstPartyHosts = [\"dash.lumai.ir\", \"ir.lumai.ir\"];\n\nfunction json(body: unknown, status = 200, headers: Record<string, string> = {}) {\n return new Response(JSON.stringify(body), {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Cache-Control\": \"no-store, private, max-age=0\",\n ...headers,\n },\n });\n}\n\nconst docs = \"https://dash.lumai.ir/docs/react/troubleshooting\";\n\n/** Error response with a stable code; the docs explain each one. */\nfunction fail(status: number, code: string, error: string, headers?: Record<string, string>) {\n return json({ error, code }, status, headers);\n}\n\n/** Server-side detail for the site owner; never sent to the browser. */\nfunction log(code: string, message: string) {\n console.error(`[@luma-ai/react] ${code}: ${message} See ${docs}#${code.toLowerCase()}`);\n}\n\nconst upstreamHints: Record<number, string> = {\n 400: \"Luma rejected the site context (for example, actions larger than the limits).\",\n 401: \"The API key is invalid or revoked. Create one at https://dash.lumai.ir/developers/api/keys.\",\n 404: \"The assistant was not found for this API key. Check assistantId and that the key belongs to the assistant's account.\",\n 429: \"Luma API rate limit reached.\",\n};\n\nfunction first(value: string | null) {\n return value?.split(\",\")[0]?.trim() || null;\n}\n\n/** The site origin this request belongs to, or null for a foreign browser origin. */\nfunction siteOrigin(request: Request, siteUrl?: string) {\n const origin = request.headers.get(\"origin\");\n try {\n if (siteUrl) {\n const site = new URL(siteUrl).origin;\n return origin && origin !== site ? null : site;\n }\n const url = new URL(request.url);\n const host =\n first(request.headers.get(\"x-forwarded-host\")) ??\n request.headers.get(\"host\") ??\n url.host;\n if (origin) {\n const parsed = new URL(origin);\n return parsed.host === host ? parsed.origin : null;\n }\n const protocol =\n first(request.headers.get(\"x-forwarded-proto\")) ?? url.protocol.slice(0, -1);\n return new URL(`${protocol}://${host}`).origin;\n } catch {\n return null;\n }\n}\n\n/**\n * Creates the POST handler that starts visitor sessions for LumaProvider's sessionEndpoint.\n * It uses the Fetch API, so it works as a Next.js route handler, a TanStack Start server\n * route, a React Router action, or in any runtime with Request/Response.\n */\nexport function createLumaSessionHandler(options: LumaSessionHandlerOptions) {\n const apiBaseUrl = (\n options.apiBaseUrl ?? API_BASE_URLS[options.server ?? \"internal\"]\n ).replace(/\\/+$/, \"\");\n const browserApiBaseUrl = (options.browserApiBaseUrl ?? apiBaseUrl).replace(\n /\\/+$/,\n \"\",\n );\n const allowed = new Set<SiteToolName>(options.capabilities ?? siteToolNames);\n return async function handleLumaSession(request: Request): Promise<Response> {\n if (request.method !== \"POST\")\n return fail(405, \"LUMA_METHOD_NOT_ALLOWED\", \"Method not allowed\", { Allow: \"POST\" });\n if (!options.apiKey || !options.assistantId) {\n log(\n \"LUMA_NOT_CONFIGURED\",\n `createLumaSessionHandler needs apiKey and assistantId (missing: ${[\n !options.apiKey && \"apiKey\",\n !options.assistantId && \"assistantId\",\n ]\n .filter(Boolean)\n .join(\", \")}). Set LUMA_API_KEY and LUMA_ASSISTANT_ID on the server.`,\n );\n return fail(503, \"LUMA_NOT_CONFIGURED\", \"Assistant unavailable\");\n }\n // Reject cross-site browser requests. This is not visitor authentication.\n const origin = siteOrigin(request, options.siteUrl);\n if (!origin || request.headers.get(\"sec-fetch-site\") === \"cross-site\")\n return fail(403, \"LUMA_ORIGIN_NOT_ALLOWED\", \"Origin not allowed\");\n const verdict = await options.authorize?.(request);\n if (verdict instanceof Response) return verdict;\n if (verdict === false) return fail(403, \"LUMA_FORBIDDEN\", \"Forbidden\");\n\n const text = await request.text();\n if (text.length > 16000) return fail(413, \"LUMA_INVALID_REQUEST\", \"Request too large\");\n let body: { capabilities?: unknown };\n try {\n body = text ? JSON.parse(text) : {};\n } catch {\n return fail(400, \"LUMA_INVALID_REQUEST\", \"Invalid request\");\n }\n const requested = Array.isArray(body?.capabilities)\n ? body.capabilities.filter((name): name is SiteToolName =>\n siteToolNames.includes(name as SiteToolName),\n )\n : defaultCapabilities;\n const actions = (options.actions ?? []).map(actionContract);\n const capabilities = [...new Set(requested)].filter(\n (name) => allowed.has(name) && (name !== \"runAction\" || actions.length),\n );\n const parsed = siteContextSchema.safeParse({\n version: 1,\n origin,\n capabilities,\n ...(capabilities.includes(\"showGuide\") ? { features: [\"guideTour\"] } : {}),\n ...(capabilities.includes(\"runAction\") ? { actions } : {}),\n });\n if (!parsed.success) {\n log(\n \"LUMA_INVALID_SITE_CONTEXT\",\n `The site context is invalid: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"context\"}: ${issue.message}`)\n .join(\"; \")}. Check the actions passed to createLumaSessionHandler (at most 20, schemas up to 4000 characters).`,\n );\n return fail(500, \"LUMA_INVALID_SITE_CONTEXT\", \"Assistant unavailable\");\n }\n const site = parsed.data;\n const resume = request.headers.get(\"x-session-id\");\n let response: Response;\n try {\n response = await (options.fetch ?? fetch)(\n `${apiBaseUrl}/assistant/${encodeURIComponent(options.assistantId)}/session`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"x-api-key\": options.apiKey,\n },\n body: JSON.stringify({\n site,\n ...(resume && /^[A-Za-z0-9_-]{16,200}$/.test(resume)\n ? { sessionId: resume }\n : {}),\n }),\n // Never forward the API key to a redirect target.\n redirect: \"manual\",\n cache: \"no-store\",\n signal: AbortSignal.timeout(15000),\n },\n );\n } catch (error) {\n log(\n \"LUMA_UPSTREAM_UNREACHABLE\",\n `Could not reach ${apiBaseUrl} (${error instanceof Error ? error.message : \"network error\"}). Try server: \"${options.server === \"direct\" ? \"internal\" : \"direct\"}\" if this host cannot reach it.`,\n );\n return fail(502, \"LUMA_UPSTREAM_UNREACHABLE\", \"Unable to create session\");\n }\n if (!response.ok) {\n log(\n \"LUMA_UPSTREAM_REJECTED\",\n `Luma returned HTTP ${response.status}. ${upstreamHints[response.status] ?? \"\"}`.trim(),\n );\n return fail(502, \"LUMA_UPSTREAM_REJECTED\", \"Unable to create session\");\n }\n const payload = (await response.json().catch(() => null)) as {\n success?: boolean;\n data?: Record<string, unknown>;\n } | null;\n const data = payload?.data;\n if (\n payload?.success !== true ||\n !data ||\n typeof data.sessionId !== \"string\" ||\n !data.sessionId.trim()\n ) {\n log(\"LUMA_UPSTREAM_REJECTED\", \"Luma returned an unexpected session response.\");\n return fail(502, \"LUMA_UPSTREAM_REJECTED\", \"Unable to create session\");\n }\n let avatar =\n typeof data.avatar === \"string\" && /^https?:\\/\\//.test(data.avatar)\n ? data.avatar\n : null;\n // Route first-party avatar assets through the selected server too.\n if (\n avatar &&\n /^https?:\\/\\//.test(browserApiBaseUrl) &&\n firstPartyHosts.includes(new URL(avatar).host)\n )\n avatar = avatar.replace(\n /^https?:\\/\\/[^/]+/,\n browserApiBaseUrl.replace(/\\/api$/, \"\"),\n );\n // Explicit allowlist avoids leaking future upstream response fields.\n return json({\n assistantId: options.assistantId,\n sessionId: data.sessionId,\n name: typeof data.name === \"string\" ? data.name : \"\",\n color: typeof data.color === \"string\" ? data.color : \"blue\",\n avatar,\n siteContext: site,\n chatEndpoint: `${browserApiBaseUrl}/assistant/chat/widget`,\n });\n };\n}\n"],"mappings":";;AAEA,IAAa,gBAAgB;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAM,OAAO,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,GAAG;AACtC,IAAM,YAAY,EAAE,OAAO;CACzB,UAAU,KAAK,IAAI,CAAC;CACpB,OAAO,KAAK,IAAI,CAAC;CACjB,aAAa,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI;CAC9C,YAAY,EAAE,KAAK;EAAC;EAAQ;EAAS;EAAU;CAAU,CAAC;CAC1D,kBAAkB,KACf,SAAS,CAAC,CACV,SAAS,CAAC,CACV,SACC,kFACF;AACJ,CAAC;AAEW,EAAE,OAAO,CAAC,CAAC,GACT,EAAE,OAAO;CACnB,O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Q,YAAY,QAAQ,IAAK;GACnC,CACF;EACF,SAAS,OAAO;GACd,IACE,6BACA,mBAAmB,WAAW,IAAI,iBAAiB,QAAQ,MAAM,UAAU,gBAAgB,kBAAkB,QAAQ,WAAW,WAAW,aAAa,SAAS,gCACnK;GACA,OAAO,KAAK,KAAK,6BAA6B,0BAA0B;EAC1E;EACA,IAAI,CAAC,SAAS,IAAI;GAChB,IACE,0BACA,sBAAsB,SAAS,OAAO,IAAI,cAAc,SAAS,WAAW,KAAK,KAAK,CACxF;GACA,OAAO,KAAK,KAAK,0BAA0B,0BAA0B;EACvE;EACA,MAAM,UAAW,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,IAAI;EAIvD,MAAM,OAAO,SAAS;EACtB,IACE,SAAS,YAAY,QACrB,CAAC,QACD,OAAO,KAAK,cAAc,YAC1B,CAAC,KAAK,UAAU,KAAK,GACrB;GACA,IAAI,0BAA0B,+CAA+C;GAC7E,OAAO,KAAK,KAAK,0BAA0B,0BAA0B;EACvE;EACA,IAAI,SACF,OAAO,KAAK,WAAW,YAAY,eAAe,KAAK,KAAK,MAAM,IAC9D,KAAK,SACL;EAEN,IACE,UACA,eAAe,KAAK,iBAAiB,KACrC,gBAAgB,SAAS,IAAI,IAAI,MAAM,CAAC,CAAC,IAAI,GAE7C,SAAS,OAAO,QACd,qBACA,kBAAkB,QAAQ,UAAU,EAAE,CACxC;EAEF,OAAO,KAAK;GACV,aAAa,QAAQ;GACrB,WAAW,KAAK;GAChB,MAAM,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO;GAClD,OAAO,OAAO,KAAK,UAAU,WAAW,KAAK,QAAQ;GACrD;GACA,aAAa;GACb,cAAc,GAAG,kBAAkB;EACrC,CAAC;CACH;AACF"}
@@ -0,0 +1,7 @@
1
+ import { i as defineAction, n as LumaServer, r as LumaActionDefinition, t as LumaAppearance } from "./config-CCT7m9eE.js";
2
+ import { _ as LumaProductQuery, a as useLumaAction, c as LumaState, d as LumaProviderProps, f as LumaNavigation, g as LumaProduct, h as LumaLink, i as useLuma, l as LumaStatus, m as LumaDataSources, n as lumaPrivate, o as useLumaContext, p as LumaDataSourceContext, r as LumaPrivate, s as LumaActionHandler, t as lumaLabel, v as LumaSearchResult, y as LumaSiteInfo } from "./index-BdkoFDyP.js";
3
+ //#region src/tanstack.d.ts
4
+ /** LumaProvider for TanStack Router and TanStack Start. Render it inside the router (root route). */
5
+ export declare function LumaProvider(props: Omit<LumaProviderProps, "navigator">): import("react").JSX.Element;
6
+ //#endregion
7
+ export { type LumaActionDefinition, type LumaActionHandler, type LumaAppearance, type LumaDataSourceContext, type LumaDataSources, type LumaLink, type LumaNavigation, LumaPrivate, type LumaProduct, type LumaProductQuery, type LumaProviderProps, type LumaSearchResult, type LumaServer, type LumaSiteInfo, type LumaState, type LumaStatus, defineAction, lumaLabel, lumaPrivate, useLuma, useLumaAction, useLumaContext };
@@ -0,0 +1,22 @@
1
+ "use client";
2
+ import { a as useLumaAction, c as routerPath, i as useLuma, l as defineAction, n as lumaPrivate, o as useLumaContext, r as LumaPrivate, s as LumaProvider$1, t as lumaLabel } from "./chunks/src-dnp1waFV.js";
3
+ import { useMemo } from "react";
4
+ import { jsx } from "react/jsx-runtime";
5
+ import { useRouter } from "@tanstack/react-router";
6
+ //#region src/tanstack.tsx
7
+ /** LumaProvider for TanStack Router and TanStack Start. Render it inside the router (root route). */
8
+ function LumaProvider(props) {
9
+ const router = useRouter();
10
+ const navigator = useMemo(() => ({
11
+ client: true,
12
+ navigate: (url) => void router.navigate({ href: routerPath(url) })
13
+ }), [router]);
14
+ return /* @__PURE__ */ jsx(LumaProvider$1, {
15
+ ...props,
16
+ navigator
17
+ });
18
+ }
19
+ //#endregion
20
+ export { LumaPrivate, LumaProvider, defineAction, lumaLabel, lumaPrivate, useLuma, useLumaAction, useLumaContext };
21
+
22
+ //# sourceMappingURL=tanstack.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tanstack.js","names":["BaseProvider"],"sources":["../src/tanstack.tsx"],"sourcesContent":["import { useMemo } from \"react\";\nimport { useRouter } from \"@tanstack/react-router\";\nimport { LumaProvider as BaseProvider, type LumaProviderProps } from \"./provider\";\nimport { routerPath, type LumaNavigation } from \"./core/navigation\";\n\n// Library entry: re-export the full client API next to the router-aware provider.\n// oxlint-disable-next-line react/only-export-components\nexport * from \"./index\";\n\n/** LumaProvider for TanStack Router and TanStack Start. Render it inside the router (root route). */\nexport function LumaProvider(props: Omit<LumaProviderProps, \"navigator\">) {\n const router = useRouter();\n const navigator = useMemo<LumaNavigation>(\n // href is the public URL, including any basepath.\n () => ({ client: true, navigate: (url) => void router.navigate({ href: routerPath(url) }) }),\n [router],\n );\n return <BaseProvider {...props} navigator={navigator} />;\n}\n"],"mappings":";;;;;;;AAUA,SAAgB,aAAa,OAA6C;CACxE,MAAM,SAAS,UAAU;CACzB,MAAM,YAAY,eAET;EAAE,QAAQ;EAAM,WAAW,QAAQ,KAAK,OAAO,SAAS,EAAE,MAAM,WAAW,GAAG,EAAE,CAAC;CAAE,IAC1F,CAAC,MAAM,CACT;CACA,OAAO,oBAACA,gBAAD;EAAc,GAAI;EAAkB;CAAY,CAAA;AACzD"}
@@ -0,0 +1,71 @@
1
+ ---
2
+ title: اقدام‌ها
3
+ description: تعریف کارهایی که دستیار می‌تواند در اپ انجام دهد، مثل افزودن به سبد، با defineAction و useLumaAction و تأیید بازدیدکننده.
4
+ ---
5
+
6
+ دستیار می‌تواند انجام کاری را در اپ پیشنهاد دهد، مثل افزودن محصول به سبد خرید. بازدیدکننده پیش از اجرا یک کارت تأیید می‌بیند و فقط با «انجام شود» اقدام اجرا می‌شود. کد اقدام را خودتان می‌نویسید؛ دستیار هرگز کد دلخواه اجرا نمی‌کند.
7
+
8
+ ## ۱. تعریف در یک فایل مشترک
9
+
10
+ ```ts
11
+ // lib/luma-actions.ts
12
+ import { z } from "zod";
13
+ import { defineAction } from "@luma-ai/react/server";
14
+
15
+ export const addToCart = defineAction({
16
+ name: "addToCart",
17
+ title: "افزودن به سبد خرید", // برچسب فارسی کارت تأیید
18
+ description: "Add the product the visitor is viewing to their cart.", // برای مدل
19
+ input: z.object({
20
+ productId: z.string(),
21
+ quantity: z.number().int().min(1).max(5),
22
+ }),
23
+ // confirm: false ← فقط برای کارهای بی‌خطر و برگشت‌پذیر
24
+ });
25
+ ```
26
+
27
+ `defineAction` از هر دو ورودی `@luma-ai/react` و `@luma-ai/react/server` در دسترس است و کد React ندارد، پس فایل در سرور و مرورگر قابل import است. نام فقط حروف انگلیسی، رقم، `_` و `-` است و با حرف شروع می‌شود.
28
+
29
+ ## ۲. معرفی به دستیار
30
+
31
+ **روش سرور:** در handler نشست:
32
+
33
+ ```ts
34
+ createLumaSessionHandler({ apiKey, assistantId, actions: [addToCart] });
35
+ ```
36
+
37
+ **روش بدون کلید:** به Provider:
38
+
39
+ ```tsx
40
+ <LumaProvider assistantId="<ASSISTANT_ID>" actions={[addToCart]}>
41
+ ```
42
+
43
+ ## ۳. اجرا در کامپوننتی که وضعیت را دارد
44
+
45
+ ```tsx
46
+ "use client";
47
+ import { useLumaAction } from "@luma-ai/react";
48
+ import { addToCart } from "@/lib/luma-actions";
49
+
50
+ export function ProductPage({ product }: { product: Product }) {
51
+ const cart = useCart();
52
+ useLumaAction(addToCart, async ({ productId, quantity }) => {
53
+ if (productId !== product.id) throw new Error("Another product is open.");
54
+ await cart.add(productId, quantity);
55
+ return { cartItems: cart.count + quantity }; // نتیجه JSON به دستیار گزارش می‌شود
56
+ });
57
+ // ...
58
+ }
59
+ ```
60
+
61
+ - اقدام فقط در صفحه‌هایی در دسترس است که کامپوننت ثبت‌کننده mount شده باشد. در صفحه‌های دیگر دستیار پیام «در این صفحه در دسترس نیست» می‌گیرد.
62
+ - ورودی پیش از اجرا با همان schema اعتبارسنجی می‌شود. اگر بازدیدکننده روی «انجام شود» کلیک کند و handler در این فاصله حذف شده باشد، اقدام اجرا نمی‌شود.
63
+ - خطای پرتاب‌شده با متن آن به دستیار گزارش می‌شود؛ متن خطا را برای مدل قابل فهم بنویسید.
64
+ - نتیجه باید قابل تبدیل به JSON باشد و از ۴۸ کیلوبایت کمتر.
65
+ - تعریف را در سطح ماژول بسازید، نه داخل کامپوننت، تا هویت آن ثابت بماند.
66
+
67
+ ## محدودیت‌ها
68
+
69
+ - حداکثر ۲۰ اقدام در هر نشست؛ schema هر اقدام حداکثر ۴۰۰۰ کاراکتر JSON Schema.
70
+ - در روش سرور، فقط اقدام‌هایی که در `actions` handler معرفی شده‌اند به دستیار گفته می‌شوند. اگر `useLumaAction` اقدامی را ثبت کند که معرفی نشده، کنسول هشدار `LUMA_ACTION_NOT_DECLARED` می‌دهد.
71
+ - اقدام‌های بدون تأیید (`confirm: false`) فوراً اجرا می‌شوند؛ از آن‌ها برای کارهای مالی یا غیرقابل برگشت استفاده نکنید.
@@ -0,0 +1,71 @@
1
+ ---
2
+ title: استفاده با دستیارهای کدنویسی
3
+ description: مستندات Markdown، llms.txt، فایل‌های داخل node_modules و skill بسته برای Claude Code، Cursor، Codex و ابزارهای مشابه.
4
+ ---
5
+
6
+ این مستندات برای دستیارهای کدنویسی هم در دسترس است، بدون نیاز به ورود به داشبورد.
7
+
8
+ ## ساده‌ترین راه
9
+
10
+ در داشبورد لوما ← دستیار ← نمای کلی ← «افزودن به وب‌سایت»، دکمه «کپی دستور برای دستیار کدنویسی» را بزنید و متن را به دستیار کدنویسی بدهید. این متن شناسه دستیار، روش اتصال و آدرس مستندات را دارد.
11
+
12
+ ## مستندات Markdown
13
+
14
+ | آدرس | محتوا |
15
+ | --- | --- |
16
+ | `https://dash.lumai.ir/llms.txt` | فهرست مستندات با لینک نسخه Markdown هر صفحه ([llms.txt](https://llmstxt.org)) |
17
+ | `https://dash.lumai.ir/llms-full.txt` | همه مستندات در یک فایل |
18
+ | `https://dash.lumai.ir/docs/react/<صفحه>.md` | نسخه Markdown هر صفحه، مثلاً `/docs/react/actions.md` |
19
+
20
+ درخواست صفحه‌های مستندات با هدر `Accept: text/markdown` هم به‌جای HTML، Markdown برمی‌گرداند.
21
+
22
+ ## مستندات داخل بسته
23
+
24
+ همین مستندات، هم‌نسخه با بسته نصب‌شده، داخل `node_modules` قرار دارد و بدون اینترنت قابل خواندن است:
25
+
26
+ ```
27
+ node_modules/@luma-ai/react/docs/index.md ← فهرست
28
+ node_modules/@luma-ai/react/skills/luma-ai-react/SKILL.md
29
+ ```
30
+
31
+ typeهای بسته هم توضیح هر گزینه را دارند، پس ویرایشگر و دستیار کدنویسی آن‌ها را مستقیم می‌بینند.
32
+
33
+ ## Skill
34
+
35
+ بسته یک [Agent Skill](https://agentskills.io) دارد: دستورالعمل کوتاه برای انتخاب روش اتصال، الگوهای درست و اشتباه‌های رایج.
36
+
37
+ **با [TanStack Intent](https://tanstack.com/intent/latest/docs/overview):** یک بار در پروژه اجرا کنید. Intent skillهای بسته‌های نصب‌شده را پیدا می‌کند و در `AGENTS.md` ثبت می‌کند:
38
+
39
+ ```sh
40
+ npx @tanstack/intent@latest install
41
+ ```
42
+
43
+ **دستی، برای Claude Code:**
44
+
45
+ ```sh
46
+ mkdir -p .claude/skills && cp -r node_modules/@luma-ai/react/skills/luma-ai-react .claude/skills/
47
+ ```
48
+
49
+ برای ابزارهای دیگر، پوشه را در محل skillهای همان ابزار کپی کنید. نسخه کپی‌شده با به‌روزرسانی بسته به‌روز نمی‌شود؛ پس از ارتقا دوباره کپی کنید.
50
+
51
+ ## AGENTS.md
52
+
53
+ اگر نمی‌خواهید skill نصب کنید، این بخش را به `AGENTS.md` (یا `CLAUDE.md`) پروژه اضافه کنید:
54
+
55
+ ```md
56
+ ## Luma assistant (@luma-ai/react)
57
+
58
+ Before writing or changing code that uses @luma-ai/react, read
59
+ node_modules/@luma-ai/react/skills/luma-ai-react/SKILL.md and the relevant pages in
60
+ node_modules/@luma-ai/react/docs/. They match the installed version.
61
+ ```
62
+
63
+ ## کارهایی که دستیار کدنویسی نمی‌تواند انجام دهد
64
+
65
+ این مراحل در داشبورد و با حساب شما انجام می‌شود؛ دستیار کدنویسی باید آن‌ها را از شما بخواهد:
66
+
67
+ - ساخت دستیار و برداشتن شناسه آن.
68
+ - ساخت کلید API و قرار دادن آن در متغیر محیطی سرور.
69
+ - روشن کردن «دسترسی بدون کلید» و افزودن دامنه‌های مجاز.
70
+
71
+ پس از اجرا، اگر ویجت وصل نشد، کنسول مرورگر کد خطا را نشان می‌دهد؛ راه‌حل هر کد در [عیب‌یابی](./troubleshooting.md) آمده است.
@@ -0,0 +1,90 @@
1
+ ---
2
+ title: داده زنده سایت
3
+ description: معرفی نام سایت، منوها، صفحه‌ها، جستجو و محصولات به دستیار با dataSources؛ همه در مرورگر اجرا می‌شوند.
4
+ ---
5
+
6
+ دستیار فقط چیزهایی از سایت را می‌داند که در اختیارش بگذارید. `dataSources` توابع و داده‌هایی است که دستیار هنگام گفتگو صدا می‌زند. همه آن‌ها در مرورگر بازدیدکننده اجرا می‌شوند؛ برای داده سروری، API خودتان را با `fetch` صدا بزنید.
7
+
8
+ ```tsx
9
+ <LumaProvider
10
+ sessionEndpoint="/api/luma/session"
11
+ dataSources={{
12
+ site: {
13
+ name: "فروشگاه من",
14
+ currency: "تومان",
15
+ menus: [{ title: "ارسال و مرجوعی", url: "/shipping" }],
16
+ pages: [
17
+ { title: "شرایط مرجوعی", url: "/returns", description: "هفت روز ضمانت بازگشت" },
18
+ ],
19
+ },
20
+ searchProducts: async ({ query, maxPrice, inStock, page }, { signal }) => {
21
+ const params = new URLSearchParams({ q: query, page: String(page) });
22
+ if (maxPrice != null) params.set("max", String(maxPrice));
23
+ if (inStock) params.set("inStock", "1");
24
+ return (await fetch(`/api/products?${params}`, { signal })).json(); // { items: LumaProduct[] }
25
+ },
26
+ getProduct: async ({ productId }, { signal }) =>
27
+ (await fetch(`/api/products/${productId}`, { signal })).json(), // LumaProduct | null
28
+ }}
29
+ >
30
+ ```
31
+
32
+ هر تابع فقط وقتی به دستیار معرفی می‌شود که آن را تعریف کرده باشید. شیء `dataSources` می‌تواند در هر رندر عوض شود؛ گفتگوی باز همیشه آخرین نسخه را صدا می‌زند و قابلیت‌های تازه بدون شروع گفتگوی جدید فعال می‌شوند.
33
+
34
+ ## site
35
+
36
+ اطلاعات ثابت سایت (`LumaSiteInfo`)، یا تابعی که آن را برمی‌گرداند:
37
+
38
+ | فیلد | توضیح |
39
+ | --- | --- |
40
+ | `name` | نام سایت. پیش‌فرض: عنوان صفحه |
41
+ | `language` | زبان. پیش‌فرض: `lang` سند |
42
+ | `currency` | واحد پول قیمت‌ها |
43
+ | `menus` | لینک‌های اصلی: `{ title, url, description?, id? }[]` |
44
+ | `pages` | فهرست صفحه‌های عمومی؛ بدون `searchSite`، جستجو روی همین فهرست انجام می‌شود |
45
+
46
+ فیلدهای دیگر هم بدون تغییر به دستیار داده می‌شوند. بدون `dataSources` هم دستیار نام، زبان و آدرس سایت را از خود صفحه می‌خواند.
47
+
48
+ ## searchSite
49
+
50
+ ```ts
51
+ searchSite: async ({ query, page }, { signal }) => ({ items: LumaLink[], hasMore?: boolean })
52
+ ```
53
+
54
+ اختیاری است. بدون آن، جستجو روی `site.pages` انجام می‌شود. هر صفحه حداکثر ۱۲ نتیجه دارد.
55
+
56
+ ## searchProducts و getProduct
57
+
58
+ ```ts
59
+ searchProducts: async (
60
+ { query, minPrice, maxPrice, category, inStock, page },
61
+ { sessionId, signal },
62
+ ) => ({ items: LumaProduct[], hasMore?: boolean })
63
+
64
+ getProduct: async ({ productId }, { sessionId, signal }) => LumaProduct | null
65
+ ```
66
+
67
+ `minPrice`، `maxPrice` و `category` ممکن است `null` باشند. حداکثر ۸ محصول در هر صفحه نمایش داده می‌شود. فیلدهای اضافه نتیجه، مثل یک توضیح درباره قیمت، بدون تغییر به دستیار می‌رسند.
68
+
69
+ `LumaProduct`:
70
+
71
+ | فیلد | الزامی | توضیح |
72
+ | --- | --- | --- |
73
+ | `productId` | بله | `string` یا `number` |
74
+ | `title` | بله | |
75
+ | `url` | بله | آدرس هم‌دامنه؛ نسبی هم قبول است |
76
+ | `price` | بله | `string` یا `number`، مثلاً `"۸۵۰٬۰۰۰ تومان"` |
77
+ | `inStock` | بله | |
78
+ | `image` | خیر | |
79
+ | `currency` | خیر | |
80
+ | `attributes` | خیر | `Record<string, string[]>`، مثلاً `{ "رنگ": ["آبی"] }` |
81
+ | `variations` | خیر | گونه‌های محصول |
82
+
83
+ نتیجه‌ها به شکل کارت محصول در گفتگو نمایش داده می‌شوند و با کلیک، صفحه محصول با مسیریاب اپ باز می‌شود.
84
+
85
+ ## قواعد
86
+
87
+ - هر تابع حداکثر ۱۵ ثانیه فرصت دارد؛ `signal` را به `fetch` بدهید تا درخواست‌های لغوشده متوقف شوند.
88
+ - اگر تابع خطا بدهد، دستیار پیام «داده زنده در دسترس نیست» می‌گیرد و قیمت یا لینک نمی‌سازد.
89
+ - فقط لینک‌های هم‌دامنه و امن قابل باز شدن هستند؛ لینک‌های خارجی، خروج از حساب و مسیرهای [محدودشده](./privacy.md) حذف می‌شوند.
90
+ - این داده‌ها به مدل ارسال می‌شوند؛ اطلاعات خصوصی کاربران را در آن‌ها نگذارید.