@01.software/cli 0.10.0 → 0.10.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.
- package/dist/index.js +209 -0
- package/dist/index.js.map +1 -1
- package/dist/mcp/{chunk-CADO6WG6.js → chunk-VSMPWKVX.js} +754 -158
- package/dist/mcp/chunk-VSMPWKVX.js.map +1 -0
- package/dist/mcp/http.js +18 -8
- package/dist/mcp/http.js.map +1 -1
- package/dist/mcp/stdio.js +1 -1
- package/dist/mcp/vercel.js +772 -166
- package/package.json +17 -9
- package/dist/mcp/chunk-CADO6WG6.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/lib/request-context.ts","../src/lib/tool-utils.ts","../../../packages/auth-contracts/src/index.ts","../../../packages/contracts/src/tenant/index.ts","../../../packages/contracts/src/ecommerce/index.ts","../../../packages/contracts/src/mcp/index.ts","../src/tool-policy.ts","../src/lib/mcp-telemetry.ts","../src/lib/console-api.ts","../src/service-auth.ts","../src/tools/query-collection.ts","../src/lib/client.ts","../src/tools/get-collection-by-id.ts","../src/tools/get-order.ts","../src/tools/create-order.ts","../src/tools/update-order.ts","../src/tools/checkout.ts","../src/tools/create-fulfillment.ts","../src/tools/update-fulfillment.ts","../src/tools/update-transaction.ts","../src/tools/create-return.ts","../src/tools/update-return.ts","../src/tools/return-with-refund.ts","../src/tools/add-cart-item.ts","../src/tools/update-cart-item.ts","../src/tools/remove-cart-item.ts","../src/tools/apply-discount.ts","../src/tools/remove-discount.ts","../src/tools/clear-cart.ts","../src/tools/validate-discount.ts","../src/tools/calculate-shipping.ts","../src/tools/stock-check.ts","../src/tools/product-detail.ts","../src/tools/product-upsert.ts","../src/tools/get-collection-schema.ts","../src/lib/collection-schema.ts","../src/lib/tenant-context.ts","../src/tools/get-tenant-context.ts","../src/tools/check-feature-progress.ts","../src/tools/list-configurable-fields.ts","../src/lib/field-config.ts","../src/tools/update-field-config.ts","../src/tools/sdk-get-recipe.ts","../src/lib/sdk-recipes.ts","../src/tools/sdk-search-docs.ts","../src/lib/sdk-doc-index.ts","../src/tools/sdk-get-auth-setup.ts","../src/tools/sdk-get-collection-pattern.ts","../src/prompts/sdk-usage-guide.ts","../src/prompts/collection-query-help.ts","../src/prompts/order-flow-guide.ts","../src/prompts/feature-setup-guide.ts","../src/resources/%28config%29/app.ts","../src/resources/%28collections%29/schema.ts","../src/resources/%28docs%29/getting-started.ts","../src/resources/%28docs%29/guides.ts","../src/resources/%28docs%29/api.ts","../src/resources/%28docs%29/query-builder.ts","../src/resources/%28docs%29/react-query.ts","../src/resources/%28docs%29/server-api.ts","../src/resources/%28docs%29/customer-auth.ts","../src/resources/%28docs%29/browser-vs-server.ts","../src/resources/%28docs%29/file-upload.ts","../src/resources/%28docs%29/webhook.ts","../src/resources/%28docs%29/product-detail.ts"],"sourcesContent":["import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { z } from 'zod'\nimport type { ToolMetadata, PromptMetadata, ResourceMetadata } from './types'\nimport { hasRequestContext, tenantAuthContext } from './lib/request-context'\nimport { toolError } from './lib/tool-utils'\nimport { evaluateToolPolicy } from './tool-policy'\nimport {\n createMcpTelemetrySummary,\n currentMcpTelemetrySummary,\n flushMcpTelemetrySummary,\n recordMcpToolResult,\n} from './lib/mcp-telemetry'\n\n// --- Tools ---\nimport queryCollectionHandler, {\n schema as queryCollectionSchema,\n metadata as queryCollectionMeta,\n} from './tools/query-collection'\nimport getCollectionByIdHandler, {\n schema as getCollectionByIdSchema,\n metadata as getCollectionByIdMeta,\n} from './tools/get-collection-by-id'\nimport getOrderHandler, {\n schema as getOrderSchema,\n metadata as getOrderMeta,\n} from './tools/get-order'\nimport createOrderHandler, {\n schema as createOrderSchema,\n metadata as createOrderMeta,\n} from './tools/create-order'\nimport updateOrderHandler, {\n schema as updateOrderSchema,\n metadata as updateOrderMeta,\n} from './tools/update-order'\nimport checkoutHandler, {\n schema as checkoutSchema,\n metadata as checkoutMeta,\n} from './tools/checkout'\nimport createFulfillmentHandler, {\n schema as createFulfillmentSchema,\n metadata as createFulfillmentMeta,\n} from './tools/create-fulfillment'\nimport updateFulfillmentHandler, {\n schema as updateFulfillmentSchema,\n metadata as updateFulfillmentMeta,\n} from './tools/update-fulfillment'\nimport updateTransactionHandler, {\n schema as updateTransactionSchema,\n metadata as updateTransactionMeta,\n} from './tools/update-transaction'\nimport createReturnHandler, {\n schema as createReturnSchema,\n metadata as createReturnMeta,\n} from './tools/create-return'\nimport updateReturnHandler, {\n schema as updateReturnSchema,\n metadata as updateReturnMeta,\n} from './tools/update-return'\nimport returnWithRefundHandler, {\n schema as returnWithRefundSchema,\n metadata as returnWithRefundMeta,\n} from './tools/return-with-refund'\nimport addCartItemHandler, {\n schema as addCartItemSchema,\n metadata as addCartItemMeta,\n} from './tools/add-cart-item'\nimport updateCartItemHandler, {\n schema as updateCartItemSchema,\n metadata as updateCartItemMeta,\n} from './tools/update-cart-item'\nimport removeCartItemHandler, {\n schema as removeCartItemSchema,\n metadata as removeCartItemMeta,\n} from './tools/remove-cart-item'\nimport applyDiscountHandler, {\n schema as applyDiscountSchema,\n metadata as applyDiscountMeta,\n} from './tools/apply-discount'\nimport removeDiscountHandler, {\n schema as removeDiscountSchema,\n metadata as removeDiscountMeta,\n} from './tools/remove-discount'\nimport clearCartHandler, {\n schema as clearCartSchema,\n metadata as clearCartMeta,\n} from './tools/clear-cart'\nimport validateDiscountHandler, {\n schema as validateDiscountSchema,\n metadata as validateDiscountMeta,\n} from './tools/validate-discount'\nimport calculateShippingHandler, {\n schema as calculateShippingSchema,\n metadata as calculateShippingMeta,\n} from './tools/calculate-shipping'\nimport stockCheckHandler, {\n schema as stockCheckSchema,\n metadata as stockCheckMeta,\n} from './tools/stock-check'\nimport productDetailHandler, {\n schema as productDetailSchema,\n metadata as productDetailMeta,\n} from './tools/product-detail'\nimport productUpsertHandler, {\n schema as productUpsertSchema,\n metadata as productUpsertMeta,\n} from './tools/product-upsert'\nimport getCollectionSchemaHandler, {\n schema as getCollectionSchemaSchema,\n metadata as getCollectionSchemaMeta,\n} from './tools/get-collection-schema'\nimport getTenantContextHandler, {\n schema as getTenantContextSchema,\n metadata as getTenantContextMeta,\n} from './tools/get-tenant-context'\nimport checkFeatureProgressHandler, {\n schema as checkFeatureProgressSchema,\n metadata as checkFeatureProgressMeta,\n} from './tools/check-feature-progress'\n\n// Field Config (2)\nimport listConfigurableFieldsHandler, {\n schema as listConfigurableFieldsSchema,\n metadata as listConfigurableFieldsMeta,\n} from './tools/list-configurable-fields'\nimport updateFieldConfigHandler, {\n schema as updateFieldConfigSchema,\n metadata as updateFieldConfigMeta,\n} from './tools/update-field-config'\n\n// Guidance Tools (4)\nimport sdkGetRecipeHandler, {\n schema as sdkGetRecipeSchema,\n metadata as sdkGetRecipeMeta,\n} from './tools/sdk-get-recipe'\nimport sdkSearchDocsHandler, {\n schema as sdkSearchDocsSchema,\n metadata as sdkSearchDocsMeta,\n} from './tools/sdk-search-docs'\nimport sdkGetAuthSetupHandler, {\n schema as sdkGetAuthSetupSchema,\n metadata as sdkGetAuthSetupMeta,\n} from './tools/sdk-get-auth-setup'\nimport sdkGetCollectionPatternHandler, {\n schema as sdkGetCollectionPatternSchema,\n metadata as sdkGetCollectionPatternMeta,\n} from './tools/sdk-get-collection-pattern'\n\n// --- Prompts ---\nimport sdkUsageGuideHandler, {\n schema as sdkUsageGuideSchema,\n metadata as sdkUsageGuideMeta,\n} from './prompts/sdk-usage-guide'\nimport collectionQueryHelpHandler, {\n schema as collectionQueryHelpSchema,\n metadata as collectionQueryHelpMeta,\n} from './prompts/collection-query-help'\nimport orderFlowGuideHandler, {\n schema as orderFlowGuideSchema,\n metadata as orderFlowGuideMeta,\n} from './prompts/order-flow-guide'\nimport featureSetupGuideHandler, {\n schema as featureSetupGuideSchema,\n metadata as featureSetupGuideMeta,\n} from './prompts/feature-setup-guide'\n\n// --- Resources ---\nimport appConfigHandler, {\n metadata as appConfigMeta,\n} from './resources/(config)/app'\nimport collectionsSchemaHandler, {\n metadata as collectionsSchemaMeta,\n} from './resources/(collections)/schema'\nimport gettingStartedHandler, {\n metadata as gettingStartedMeta,\n} from './resources/(docs)/getting-started'\nimport guidesHandler, {\n metadata as guidesMeta,\n} from './resources/(docs)/guides'\nimport apiHandler, { metadata as apiMeta } from './resources/(docs)/api'\nimport queryBuilderHandler, {\n metadata as queryBuilderMeta,\n} from './resources/(docs)/query-builder'\nimport reactQueryHandler, {\n metadata as reactQueryMeta,\n} from './resources/(docs)/react-query'\nimport serverApiHandler, {\n metadata as serverApiMeta,\n} from './resources/(docs)/server-api'\nimport customerAuthHandler, {\n metadata as customerAuthMeta,\n} from './resources/(docs)/customer-auth'\nimport browserVsServerHandler, {\n metadata as browserVsServerMeta,\n} from './resources/(docs)/browser-vs-server'\nimport fileUploadHandler, {\n metadata as fileUploadMeta,\n} from './resources/(docs)/file-upload'\nimport webhookHandler, {\n metadata as webhookMeta,\n} from './resources/(docs)/webhook'\nimport productDetailDocHandler, {\n metadata as productDetailDocMeta,\n} from './resources/(docs)/product-detail'\n\nconst REGISTERED_TOOLS_BY_SERVER = new WeakMap<McpServer, Set<string>>()\n\nexport function getRegisteredToolNames(server: McpServer): string[] {\n return Array.from(REGISTERED_TOOLS_BY_SERVER.get(server) ?? [])\n}\n\n/**\n * Register a tool from existing schema/metadata/handler module.\n * Handlers return strings (JSON via toolSuccess/toolError), which we wrap in MCP content format.\n *\n * For HTTP MCP requests (those with a TenantAuthContext), the wrapper enforces\n * the tool-policy manifest before invoking the handler. stdio requests have no\n * request-scoped context and bypass this check; stdio is gated separately by\n * SOFTWARE_SECRET_KEY in the Console downstream layer.\n */\nfunction registerTool(\n server: McpServer,\n schema: Record<string, z.ZodType>,\n meta: ToolMetadata,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (params: any) => Promise<string> | string,\n) {\n let registered = REGISTERED_TOOLS_BY_SERVER.get(server)\n if (!registered) {\n registered = new Set()\n REGISTERED_TOOLS_BY_SERVER.set(server, registered)\n }\n registered.add(meta.name)\n\n server.registerTool(\n meta.name,\n {\n description: meta.description,\n inputSchema: schema,\n annotations: meta.annotations,\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async (params: any) => {\n const ctx = tenantAuthContext()\n if (ctx) {\n const decision = evaluateToolPolicy(meta.name, ctx.scopes)\n if (!decision.allowed) {\n const status = decision.reason === 'insufficient_scope' ? 403 : 500\n return {\n content: [\n {\n type: 'text' as const,\n text: toolError({\n status,\n reason: decision.reason,\n message: decision.message,\n }),\n },\n ],\n }\n }\n }\n const activeSummary = currentMcpTelemetrySummary()\n const ownSummary =\n activeSummary || hasRequestContext()\n ? null\n : createMcpTelemetrySummary('stdio')\n const summary = activeSummary ?? ownSummary\n let result: string | null = null\n try {\n result = await handler(params)\n return { content: [{ type: 'text' as const, text: result }] }\n } finally {\n if (summary) {\n recordMcpToolResult({\n resultText: result,\n summary,\n toolName: meta.name,\n })\n }\n if (ownSummary) {\n void flushMcpTelemetrySummary(ownSummary)\n }\n }\n },\n )\n}\n\n/**\n * Register a prompt from existing schema/metadata/handler module.\n */\nfunction registerPrompt(\n server: McpServer,\n schema: Record<string, z.ZodType>,\n meta: PromptMetadata,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handler: (params: any) => string,\n) {\n server.registerPrompt(\n meta.name,\n {\n title: meta.title,\n description: meta.description,\n argsSchema: schema,\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (params: any) => ({\n messages: [\n {\n role: meta.role ?? 'assistant',\n content: { type: 'text' as const, text: handler(params) },\n },\n ],\n }),\n )\n}\n\n/**\n * Register a static resource from existing metadata/handler module.\n */\nfunction registerStaticResource(\n server: McpServer,\n uri: string,\n meta: ResourceMetadata,\n handler: () => string,\n) {\n server.registerResource(\n meta.name,\n uri,\n {\n title: meta.title,\n description: meta.description,\n mimeType: meta.mimeType ?? 'text/plain',\n },\n async (url) => ({\n contents: [{ uri: url.href, text: handler() }],\n }),\n )\n}\n\nexport type ToolSurface = 'full' | 'oauth'\n\nexport interface CreateServerOptions {\n toolSurface?: ToolSurface\n}\n\nexport function createServer(options: CreateServerOptions = {}): McpServer {\n const toolSurface = options.toolSurface ?? 'full'\n const server = new McpServer({\n name: '01.software MCP Server',\n version: '0.1.0',\n })\n\n if (toolSurface === 'full') {\n // ── Full stdio tool surface (32) ──\n\n // Generic Read (2) — generic write tools are intentionally omitted;\n // tenant-admin writes use the domain-specific tools below.\n registerTool(\n server,\n queryCollectionSchema,\n queryCollectionMeta,\n queryCollectionHandler,\n )\n registerTool(\n server,\n getCollectionByIdSchema,\n getCollectionByIdMeta,\n getCollectionByIdHandler,\n )\n\n // Orders (7)\n registerTool(server, getOrderSchema, getOrderMeta, getOrderHandler)\n registerTool(server, createOrderSchema, createOrderMeta, createOrderHandler)\n registerTool(server, updateOrderSchema, updateOrderMeta, updateOrderHandler)\n registerTool(server, checkoutSchema, checkoutMeta, checkoutHandler)\n registerTool(\n server,\n createFulfillmentSchema,\n createFulfillmentMeta,\n createFulfillmentHandler,\n )\n registerTool(\n server,\n updateFulfillmentSchema,\n updateFulfillmentMeta,\n updateFulfillmentHandler,\n )\n registerTool(\n server,\n updateTransactionSchema,\n updateTransactionMeta,\n updateTransactionHandler,\n )\n\n // Returns (3)\n registerTool(\n server,\n createReturnSchema,\n createReturnMeta,\n createReturnHandler,\n )\n registerTool(\n server,\n updateReturnSchema,\n updateReturnMeta,\n updateReturnHandler,\n )\n registerTool(\n server,\n returnWithRefundSchema,\n returnWithRefundMeta,\n returnWithRefundHandler,\n )\n\n // Cart (6)\n registerTool(server, addCartItemSchema, addCartItemMeta, addCartItemHandler)\n registerTool(\n server,\n updateCartItemSchema,\n updateCartItemMeta,\n updateCartItemHandler,\n )\n registerTool(\n server,\n removeCartItemSchema,\n removeCartItemMeta,\n removeCartItemHandler,\n )\n registerTool(\n server,\n applyDiscountSchema,\n applyDiscountMeta,\n applyDiscountHandler,\n )\n registerTool(\n server,\n removeDiscountSchema,\n removeDiscountMeta,\n removeDiscountHandler,\n )\n registerTool(server, clearCartSchema, clearCartMeta, clearCartHandler)\n\n // Validation (2)\n registerTool(\n server,\n validateDiscountSchema,\n validateDiscountMeta,\n validateDiscountHandler,\n )\n registerTool(\n server,\n calculateShippingSchema,\n calculateShippingMeta,\n calculateShippingHandler,\n )\n\n // Product (3)\n registerTool(server, stockCheckSchema, stockCheckMeta, stockCheckHandler)\n registerTool(server, productDetailSchema, productDetailMeta, productDetailHandler)\n registerTool(\n server,\n productUpsertSchema,\n productUpsertMeta,\n productUpsertHandler,\n )\n }\n\n // Schema (1)\n registerTool(\n server,\n getCollectionSchemaSchema,\n getCollectionSchemaMeta,\n getCollectionSchemaHandler,\n )\n\n // Tenant Context (2)\n registerTool(\n server,\n getTenantContextSchema,\n getTenantContextMeta,\n getTenantContextHandler,\n )\n registerTool(\n server,\n checkFeatureProgressSchema,\n checkFeatureProgressMeta,\n checkFeatureProgressHandler,\n )\n\n // Field Config (2)\n registerTool(\n server,\n listConfigurableFieldsSchema,\n listConfigurableFieldsMeta,\n listConfigurableFieldsHandler,\n )\n registerTool(\n server,\n updateFieldConfigSchema,\n updateFieldConfigMeta,\n updateFieldConfigHandler,\n )\n\n // Guidance (4)\n registerTool(\n server,\n sdkGetRecipeSchema,\n sdkGetRecipeMeta,\n sdkGetRecipeHandler,\n )\n registerTool(\n server,\n sdkSearchDocsSchema,\n sdkSearchDocsMeta,\n sdkSearchDocsHandler,\n )\n registerTool(\n server,\n sdkGetAuthSetupSchema,\n sdkGetAuthSetupMeta,\n sdkGetAuthSetupHandler,\n )\n registerTool(\n server,\n sdkGetCollectionPatternSchema,\n sdkGetCollectionPatternMeta,\n sdkGetCollectionPatternHandler,\n )\n\n // ── Prompts (4) ──\n\n registerPrompt(\n server,\n sdkUsageGuideSchema,\n sdkUsageGuideMeta,\n sdkUsageGuideHandler,\n )\n registerPrompt(\n server,\n collectionQueryHelpSchema,\n collectionQueryHelpMeta,\n collectionQueryHelpHandler,\n )\n registerPrompt(\n server,\n orderFlowGuideSchema,\n orderFlowGuideMeta,\n orderFlowGuideHandler,\n )\n registerPrompt(\n server,\n featureSetupGuideSchema,\n featureSetupGuideMeta,\n featureSetupGuideHandler,\n )\n\n // ── Resources (13) ──\n\n registerStaticResource(\n server,\n 'config://app',\n appConfigMeta,\n appConfigHandler,\n )\n registerStaticResource(\n server,\n 'collections://schema',\n collectionsSchemaMeta,\n collectionsSchemaHandler,\n )\n registerStaticResource(\n server,\n 'docs://sdk/getting-started',\n gettingStartedMeta,\n gettingStartedHandler,\n )\n registerStaticResource(server, 'docs://sdk/guides', guidesMeta, guidesHandler)\n registerStaticResource(server, 'docs://sdk/api', apiMeta, apiHandler)\n registerStaticResource(\n server,\n 'docs://sdk/query-builder',\n queryBuilderMeta,\n queryBuilderHandler,\n )\n registerStaticResource(\n server,\n 'docs://sdk/react-query',\n reactQueryMeta,\n reactQueryHandler,\n )\n registerStaticResource(\n server,\n 'docs://sdk/server-api',\n serverApiMeta,\n serverApiHandler,\n )\n registerStaticResource(\n server,\n 'docs://sdk/customer-auth',\n customerAuthMeta,\n customerAuthHandler,\n )\n registerStaticResource(\n server,\n 'docs://sdk/browser-vs-server',\n browserVsServerMeta,\n browserVsServerHandler,\n )\n registerStaticResource(\n server,\n 'docs://sdk/file-upload',\n fileUploadMeta,\n fileUploadHandler,\n )\n registerStaticResource(\n server,\n 'docs://sdk/webhook',\n webhookMeta,\n webhookHandler,\n )\n registerStaticResource(\n server,\n 'docs://sdk/product-detail',\n productDetailDocMeta,\n productDetailDocHandler,\n )\n\n return server\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport type { TenantAuthContext } from '../auth'\n\nexport interface RequestContext {\n headers: Headers\n auth?: TenantAuthContext\n}\n\nexport const requestContext = new AsyncLocalStorage<RequestContext>()\n\n/**\n * Get headers from the current request context.\n * Returns null outside HTTP context (e.g. stdio transport).\n * Drop-in replacement for xmcp's `headers()`.\n */\nexport function headers(): Record<string, string> | null {\n const ctx = requestContext.getStore()\n if (!ctx) return null\n return Object.fromEntries(ctx.headers.entries())\n}\n\n/**\n * Returns the validated OAuth tenant context for HTTP MCP requests.\n * Stdio transport has no request-scoped OAuth context and returns null.\n */\nexport function tenantAuthContext(): TenantAuthContext | null {\n return requestContext.getStore()?.auth ?? null\n}\n\nexport function hasRequestContext(): boolean {\n return requestContext.getStore() !== undefined\n}\n","/**\n * Shared utilities for MCP tool handlers\n */\n\n/**\n * Format a successful tool response with both text and structured content.\n */\nexport function toolSuccess(data: Record<string, unknown>): string {\n return JSON.stringify({ success: true, ...data }, null, 2)\n}\n\n/**\n * Format a tool error response as JSON string.\n *\n * Preserves the structured fields the spec requires for cross-layer\n * supportability: `status`, `code`, `reason`, `requestId`, `suggestion`,\n * and sanitized validation `errors`. `code` carries SDK error codes,\n * `reason` carries MCP-policy denials such as `insufficient_scope`,\n * `tool_policy_missing`, `tenant_mismatch`, and `role_denied`.\n */\nexport function toolError(error: unknown): string {\n const base: Record<string, unknown> = { success: false }\n const isStructured =\n !!error && typeof error === 'object' && ('code' in error || 'reason' in error)\n\n if (isStructured) {\n const sdkErr = error as {\n message?: string\n status?: number\n code?: string\n reason?: string\n requestId?: string\n suggestion?: string\n details?: { errors?: Array<{ message?: string; field?: string }> }\n }\n base.error = sdkErr.message || 'Unknown error'\n if (sdkErr.status) base.status = sdkErr.status\n if (sdkErr.code) base.code = sdkErr.code\n if (sdkErr.reason) base.reason = sdkErr.reason\n if (sdkErr.requestId) base.requestId = sdkErr.requestId\n if (sdkErr.suggestion) base.suggestion = sdkErr.suggestion\n if (sdkErr.details?.errors) base.errors = sdkErr.details.errors\n } else {\n base.error = error instanceof Error ? error.message : 'Unknown error'\n }\n\n return JSON.stringify(base, null, 2)\n}\n\nconst MAX_QUERY_DEPTH = 5\n\nfunction checkDepth(obj: unknown, depth = 0): boolean {\n if (depth > MAX_QUERY_DEPTH) return false\n if (obj && typeof obj === 'object') {\n for (const val of Object.values(obj as Record<string, unknown>)) {\n if (!checkDepth(val, depth + 1)) return false\n }\n }\n return true\n}\n\n/**\n * Parse a JSON string \"where\" parameter.\n * Returns the parsed object on success, or a formatted error string on failure.\n * Rejects queries nested deeper than MAX_QUERY_DEPTH to prevent DoS.\n */\nexport function parseJsonWhere(\n where: string,\n):\n | { success: true; data: Record<string, unknown> }\n | { success: false; error: string } {\n try {\n const parsed = JSON.parse(where)\n\n if (!checkDepth(parsed)) {\n return {\n success: false,\n error: JSON.stringify(\n {\n success: false,\n error: `Query exceeds maximum nesting depth of ${MAX_QUERY_DEPTH}`,\n },\n null,\n 2,\n ),\n }\n }\n\n return { success: true, data: parsed }\n } catch {\n return {\n success: false,\n error: JSON.stringify(\n {\n success: false,\n error: `Invalid JSON in \"where\" parameter: ${where.length > 100 ? where.substring(0, 100) + '...' : where}`,\n },\n null,\n 2,\n ),\n }\n }\n}\n","export const MCP_RESOURCE_AUDIENCE = 'https://mcp.01.software/mcp'\n\nexport const MCP_OAUTH_ISSUER = 'https://01.software'\n\nexport const MCP_PROTECTED_RESOURCE_METADATA_PATH =\n '/.well-known/oauth-protected-resource/mcp'\n\nexport const MCP_AUTHORIZATION_SERVER_METADATA_PATH =\n '/.well-known/oauth-authorization-server'\n\nexport const MCP_TENANT_CLAIM = 'tenant_id'\n\nexport const MCP_TENANT_ROLE_CLAIM = 'tenant_role'\n\nexport const MCP_SCOPES = {\n read: 'mcp:read',\n write: 'mcp:write',\n} as const\n\nexport const MCP_CONSOLE_SERVICE_AUDIENCE =\n 'https://api.01.software/internal/mcp'\n\nexport const MCP_CONSOLE_SERVICE_SCOPE = 'console:mcp_proxy'\n\nexport const MCP_SERVICE_TOKEN_LIFETIME_SECONDS = 60\n","import { z } from 'zod'\n\nexport const tenantFieldConfigStateSchema = z\n .object({\n hiddenFields: z.array(z.string()),\n isHidden: z.boolean(),\n })\n .strict()\n\nexport const tenantContextQuerySchema = z\n .object({\n counts: z.literal('true').optional(),\n })\n .strict()\n\nexport const tenantContextToolInputSchema = z\n .object({\n includeCounts: z\n .boolean()\n .optional()\n .default(false)\n .describe(\n 'Include per-collection document counts and config status (bypasses cache, slower)',\n ),\n })\n .strict()\n\nexport const tenantContextResponseSchema = z\n .object({\n tenant: z\n .object({\n id: z.string(),\n name: z.string(),\n plan: z.string(),\n planSource: z.string().optional(),\n authoritative: z.boolean().optional(),\n capabilityVersion: z.string().optional(),\n })\n .strict(),\n features: z.array(z.string()),\n collections: z\n .object({\n active: z.array(z.string()),\n inactive: z.array(z.string()),\n })\n .strict(),\n fieldConfigs: z.record(z.string(), tenantFieldConfigStateSchema),\n counts: z.record(z.string(), z.number()).optional(),\n config: z\n .object({\n webhookConfigured: z.boolean(),\n })\n .strict()\n .optional(),\n })\n .strict()\n\nexport const tenantFeatureProgressFeatureSchema = z.enum(['ecommerce'])\n\nexport const tenantFeatureProgressInputSchema = z\n .object({\n feature: tenantFeatureProgressFeatureSchema.describe(\n 'Feature to inspect for tenant implementation readiness',\n ),\n includeEvidence: z\n .boolean()\n .optional()\n .default(false)\n .describe('Include sanitized counts and static surface evidence'),\n })\n .strict()\n\nexport const tenantFeatureProgressStatusSchema = z.enum([\n 'ready',\n 'attention',\n 'blocked',\n])\n\nexport const tenantFeatureProgressItemStateSchema = z.enum([\n 'complete',\n 'incomplete',\n 'blocked',\n 'attention',\n 'optional',\n 'unknown',\n 'manual',\n 'not-applicable',\n])\n\nexport const tenantFeatureProgressSeveritySchema = z.enum([\n 'required',\n 'recommended',\n 'optional',\n])\n\nexport const tenantFeatureProgressEvidenceValueSchema = z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.null(),\n])\n\nexport const tenantFeatureProgressItemSchema = z\n .object({\n id: z.string(),\n title: z.string(),\n state: tenantFeatureProgressItemStateSchema,\n severity: tenantFeatureProgressSeveritySchema,\n summary: z.string(),\n evidence: z\n .record(z.string(), tenantFeatureProgressEvidenceValueSchema)\n .optional(),\n })\n .strict()\n\nexport const tenantFeatureProgressGroupSchema = z\n .object({\n id: z.string(),\n title: z.string(),\n summary: z.string().optional(),\n items: z.array(tenantFeatureProgressItemSchema),\n })\n .strict()\n\nexport const tenantFeatureProgressResponseSchema = z\n .object({\n schemaVersion: z.literal(1),\n feature: tenantFeatureProgressFeatureSchema,\n status: tenantFeatureProgressStatusSchema,\n generatedAt: z.string(),\n tenant: z\n .object({\n id: z.string(),\n name: z.string(),\n plan: z.string(),\n })\n .strict(),\n capability: z\n .object({\n effectiveFeatures: z.array(z.string()),\n planBlocked: z.array(z.string()),\n closureAdded: z.array(z.string()),\n })\n .strict(),\n summary: z\n .object({\n complete: z.number().int().nonnegative(),\n total: z.number().int().nonnegative(),\n blocking: z.number().int().nonnegative(),\n manual: z.number().int().nonnegative(),\n unknown: z.number().int().nonnegative(),\n })\n .strict(),\n groups: z.array(tenantFeatureProgressGroupSchema),\n })\n .strict()\n\nexport const COLLECTION_SCHEMA_CONTRACT_VERSION = 1\n\nexport const collectionSchemaEndpointParamsSchema = z\n .object({\n collectionSlug: z.string().min(1, 'collectionSlug is required'),\n })\n .strict()\n\nexport function createCollectionSchemaToolInputSchema<\n const T extends readonly [string, ...string[]],\n>(collections: T) {\n return z\n .object({\n collection: z.enum(collections).describe('Collection name (required)'),\n })\n .strict()\n}\n\nexport const collectionFieldOptionSchema = z\n .object({\n label: z.string(),\n value: z.string(),\n })\n .strict()\n\nexport interface CollectionFieldSchema {\n name: string\n path: string\n type: string\n required?: true\n unique?: true\n hasMany?: true\n relationTo?: string | string[]\n options?: Array<{ label: string; value: string }>\n hidden?: true\n systemManaged?: true\n writable?: boolean\n fields?: CollectionFieldSchema[]\n}\n\nexport const collectionFieldSchema: z.ZodType<CollectionFieldSchema> = z.lazy(\n () =>\n z\n .object({\n name: z.string(),\n path: z.string(),\n type: z.string(),\n required: z.literal(true).optional(),\n unique: z.literal(true).optional(),\n hasMany: z.literal(true).optional(),\n relationTo: z.union([z.string(), z.array(z.string())]).optional(),\n options: z.array(collectionFieldOptionSchema).optional(),\n hidden: z.literal(true).optional(),\n systemManaged: z.literal(true).optional(),\n writable: z.boolean().optional(),\n fields: z.array(collectionFieldSchema).optional(),\n })\n .strict(),\n)\n\nexport const collectionSchemaResponseSchema = z\n .object({\n contractVersion: z.literal(COLLECTION_SCHEMA_CONTRACT_VERSION),\n mode: z.literal('effective'),\n collection: z\n .object({\n slug: z.string(),\n timestamps: z.boolean(),\n alwaysActive: z.boolean(),\n feature: z.string().nullable(),\n systemFields: z.array(z.string()),\n visibility: z\n .object({\n collectionHidden: z.boolean(),\n hiddenFields: z.array(z.string()),\n })\n .strict(),\n fields: z.array(collectionFieldSchema),\n })\n .strict(),\n })\n .strict()\n\nexport type TenantFieldConfigState = z.infer<\n typeof tenantFieldConfigStateSchema\n>\nexport type TenantContextQuery = z.input<typeof tenantContextQuerySchema>\nexport type TenantContextToolInput = z.infer<\n typeof tenantContextToolInputSchema\n>\nexport type TenantContextResponse = z.infer<typeof tenantContextResponseSchema>\nexport type TenantFeatureProgressFeature = z.infer<\n typeof tenantFeatureProgressFeatureSchema\n>\nexport type TenantFeatureProgressInput = z.infer<\n typeof tenantFeatureProgressInputSchema\n>\nexport type TenantFeatureProgressStatus = z.infer<\n typeof tenantFeatureProgressStatusSchema\n>\nexport type TenantFeatureProgressItemState = z.infer<\n typeof tenantFeatureProgressItemStateSchema\n>\nexport type TenantFeatureProgressSeverity = z.infer<\n typeof tenantFeatureProgressSeveritySchema\n>\nexport type TenantFeatureProgressEvidenceValue = z.infer<\n typeof tenantFeatureProgressEvidenceValueSchema\n>\nexport type TenantFeatureProgressItem = z.infer<\n typeof tenantFeatureProgressItemSchema\n>\nexport type TenantFeatureProgressGroup = z.infer<\n typeof tenantFeatureProgressGroupSchema\n>\nexport type TenantFeatureProgressResponse = z.infer<\n typeof tenantFeatureProgressResponseSchema\n>\nexport type CollectionSchemaEndpointParams = z.infer<\n typeof collectionSchemaEndpointParamsSchema\n>\nexport type CollectionFieldOption = z.infer<typeof collectionFieldOptionSchema>\nexport type CollectionSchemaResponse = z.infer<\n typeof collectionSchemaResponseSchema\n>\n","import { z } from 'zod'\n\nexport const transactionStatusSchema = z.enum([\n 'pending',\n 'paid',\n 'failed',\n 'canceled',\n])\n\nexport const updateTransactionSchema = z\n .object({\n pgPaymentId: z\n .string()\n .min(1, 'pgPaymentId is required')\n .describe('PG payment ID (required)'),\n status: transactionStatusSchema.describe(\n 'New transaction status (required)',\n ),\n paymentMethod: z.string().optional().describe('Payment method (optional)'),\n receiptUrl: z.string().optional().describe('Receipt URL (optional)'),\n paymentKey: z\n .string()\n .min(1)\n .optional()\n .describe('Provider payment key for verified paid confirmation'),\n amount: z\n .number()\n .int()\n .positive()\n .optional()\n .describe('Provider-confirmed amount for verified paid confirmation'),\n })\n .strict()\n\nexport const UpdateTransactionSchema = updateTransactionSchema\n\nconst providerSlugSchema = z\n .string()\n .trim()\n .regex(/^[a-z0-9][a-z0-9_-]{0,63}$/, 'pgProvider must be lowercase slug')\n\nexport const confirmPaymentSchema = z\n .object({\n orderNumber: z.string().min(1).optional(),\n pgPaymentId: z\n .string()\n .min(1, 'pgPaymentId is required')\n .describe('Provider payment identifier stored on the transaction'),\n pgProvider: providerSlugSchema.describe(\n 'Payment provider slug, e.g. toss, portone, stripe',\n ),\n pgOrderId: z.string().min(1).optional(),\n amount: z\n .number()\n .int()\n .nonnegative('amount must be non-negative')\n .describe('Provider-confirmed amount in minor units'),\n currency: z.string().min(1).optional(),\n paymentMethod: z.string().optional(),\n receiptUrl: z.string().url().optional(),\n approvedAt: z.string().optional(),\n providerStatus: z.string().optional(),\n providerEventId: z.string().min(1).optional(),\n confirmationSource: z\n .enum([\n 'provider_webhook',\n 'provider_lookup',\n 'provider_api_confirm',\n 'manual_server',\n ])\n .optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n })\n .strict()\n\nexport const ConfirmPaymentSchema = confirmPaymentSchema\n\nexport const returnReasonSchema = z.enum([\n 'change_of_mind',\n 'defective',\n 'wrong_delivery',\n 'damaged',\n 'other',\n])\n\nexport const restockActionSchema = z.enum(['return_to_stock', 'discard'])\n\nexport const returnWithRefundItemSchema = z\n .object({\n orderItem: z.union([z.string(), z.number()]).transform(String),\n quantity: z.number().int().positive('quantity must be a positive integer'),\n restockAction: restockActionSchema.default('return_to_stock'),\n restockingFee: z\n .number()\n .min(0, 'restockingFee must be non-negative')\n .optional()\n .describe('Restocking fee charged for this line (ADR 0005 §Gap 1)'),\n })\n .strict()\n\nexport const returnWithRefundSchema = z\n .object({\n orderNumber: z\n .string()\n .min(1, 'orderNumber is required')\n .describe('Order number (required)'),\n reason: returnReasonSchema.optional().describe('Return reason (optional)'),\n reasonDetail: z\n .string()\n .optional()\n .describe('Detailed reason text (optional)'),\n returnItems: z\n .array(returnWithRefundItemSchema)\n .min(1, 'At least one return item is required')\n .max(100, 'Too many return items')\n .describe('Array of products to return (required)'),\n refundAmount: z\n .number()\n .min(0, 'refundAmount must be non-negative')\n .describe('Refund amount (required, min 0)'),\n returnShippingFee: z\n .number()\n .min(0, 'returnShippingFee must be non-negative')\n .optional()\n .describe('Return shipping fee charged to the customer (ADR 0005 §Gap 1)'),\n pgPaymentId: z\n .string()\n .min(1, 'pgPaymentId is required')\n .describe('PG payment ID for refund (required)'),\n paymentKey: z\n .string()\n .min(1)\n .optional()\n .describe('Provider payment key for verified refund'),\n refundReceiptUrl: z\n .string()\n .optional()\n .describe('Refund receipt URL (optional)'),\n })\n .strict()\n\nexport const ReturnWithRefundSchema = returnWithRefundSchema\n\nexport type TransactionStatus = z.infer<typeof transactionStatusSchema>\nexport type UpdateTransactionParams = z.input<typeof UpdateTransactionSchema>\nexport type ParsedUpdateTransactionParams = z.output<\n typeof UpdateTransactionSchema\n>\nexport type ConfirmPaymentParams = z.input<typeof ConfirmPaymentSchema>\nexport type ParsedConfirmPaymentParams = z.output<typeof ConfirmPaymentSchema>\nexport type ReturnReason = z.infer<typeof returnReasonSchema>\nexport type RestockAction = z.infer<typeof restockActionSchema>\nexport type ReturnWithRefundItem = z.input<typeof returnWithRefundItemSchema>\nexport type ParsedReturnWithRefundItem = z.output<\n typeof returnWithRefundItemSchema\n>\nexport type ReturnWithRefundParams = z.input<typeof ReturnWithRefundSchema>\nexport type ParsedReturnWithRefundParams = z.output<\n typeof ReturnWithRefundSchema\n>\n","export type McpOAuthScope = 'mcp:read' | 'mcp:write'\nexport type McpConsoleRole = 'tenant-viewer' | 'tenant-editor' | 'tenant-admin'\nexport type McpTransport = 'http' | 'stdio'\n\nexport interface McpToolContractEntry {\n consoleRole: McpConsoleRole\n oauthScope: McpOAuthScope\n readOnly: boolean\n}\n\nexport const MCP_TOOL_CONTRACT = {\n 'query-collection': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'get-collection-by-id': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'get-order': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'stock-check': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'product-detail': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'product-upsert': {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'validate-discount': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'calculate-shipping': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'get-collection-schema': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'list-configurable-fields': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'get-tenant-context': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'check-feature-progress': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'add-cart-item': {\n consoleRole: 'tenant-editor',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'update-cart-item': {\n consoleRole: 'tenant-editor',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'remove-cart-item': {\n consoleRole: 'tenant-editor',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'clear-cart': {\n consoleRole: 'tenant-editor',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'apply-discount': {\n consoleRole: 'tenant-editor',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'remove-discount': {\n consoleRole: 'tenant-editor',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n checkout: {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'create-order': {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'update-order': {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'create-fulfillment': {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'update-fulfillment': {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'create-return': {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'update-return': {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'return-with-refund': {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'update-transaction': {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'update-field-config': {\n consoleRole: 'tenant-admin',\n oauthScope: 'mcp:write',\n readOnly: false,\n },\n 'sdk-get-recipe': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'sdk-search-docs': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'sdk-get-auth-setup': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n 'sdk-get-collection-pattern': {\n consoleRole: 'tenant-viewer',\n oauthScope: 'mcp:read',\n readOnly: true,\n },\n} as const satisfies Record<string, McpToolContractEntry>\n\nexport type McpToolName = keyof typeof MCP_TOOL_CONTRACT\n\nexport const MCP_TOOL_NAMES = Object.keys(MCP_TOOL_CONTRACT) as McpToolName[]\n\nexport const MCP_HTTP_DURATION_BUCKETS = [\n { key: 'le_100', label: '<=100ms', maxMs: 100 },\n { key: 'le_250', label: '<=250ms', maxMs: 250 },\n { key: 'le_500', label: '<=500ms', maxMs: 500 },\n { key: 'le_1000', label: '<=1s', maxMs: 1000 },\n { key: 'le_2500', label: '<=2.5s', maxMs: 2500 },\n { key: 'le_5000', label: '<=5s', maxMs: 5000 },\n { key: 'le_10000', label: '<=10s', maxMs: 10000 },\n { key: 'gt_10000', label: '>10s', maxMs: null },\n] as const\n\nexport type McpHttpDurationBucketKey =\n (typeof MCP_HTTP_DURATION_BUCKETS)[number]['key']\n\nexport function isMcpToolName(toolName: string): toolName is McpToolName {\n return Object.prototype.hasOwnProperty.call(MCP_TOOL_CONTRACT, toolName)\n}\n\nexport function mcpToolRequiresWrite(toolName: McpToolName): boolean {\n return MCP_TOOL_CONTRACT[toolName].oauthScope === 'mcp:write'\n}\n\nexport function mcpToolConsoleRole(toolName: McpToolName): McpConsoleRole {\n return MCP_TOOL_CONTRACT[toolName].consoleRole\n}\n\nexport function compareMcpConsoleRole(\n a: McpConsoleRole,\n b: McpConsoleRole,\n): number {\n const rank: Record<McpConsoleRole, number> = {\n 'tenant-viewer': 1,\n 'tenant-editor': 2,\n 'tenant-admin': 3,\n }\n return rank[a] - rank[b]\n}\n\nexport function maxMcpConsoleRole(\n roles: Iterable<McpConsoleRole>,\n): McpConsoleRole {\n let max: McpConsoleRole = 'tenant-viewer'\n for (const role of roles) {\n if (compareMcpConsoleRole(role, max) > 0) max = role\n }\n return max\n}\n\nexport function mcpHttpDurationBucketKey(\n durationMs: number,\n): McpHttpDurationBucketKey {\n for (const bucket of MCP_HTTP_DURATION_BUCKETS) {\n if (bucket.maxMs === null || durationMs <= bucket.maxMs) return bucket.key\n }\n return 'gt_10000'\n}\n","import { MCP_SCOPES } from '@01.software/auth-contracts'\nimport { isMcpToolName, type McpToolName } from '@01.software/contracts'\n\nexport type ToolCategory =\n | 'read-only-collection'\n | 'read-only-tenant'\n | 'mutation-cart'\n | 'mutation-order'\n | 'mutation-fulfillment'\n | 'mutation-return'\n | 'mutation-transaction'\n | 'mutation-product'\n | 'mutation-field-config'\n | 'sdk-doc'\n\nexport type ToolOAuthScope = (typeof MCP_SCOPES)[keyof typeof MCP_SCOPES]\n\nexport type ToolConsoleRole = 'tenant-viewer' | 'tenant-editor' | 'tenant-admin'\n\nexport interface ToolAnnotationPolicy {\n readOnly: boolean\n destructive: boolean\n idempotent: boolean\n openWorld: boolean\n}\n\nexport interface ToolPolicyEntry {\n category: ToolCategory\n oauthScope: ToolOAuthScope\n consoleRole: ToolConsoleRole\n consoleSurface: string\n annotationPolicy: ToolAnnotationPolicy\n exemptionReason?: string\n}\n\nconst READ_ONLY_ANNOTATION: ToolAnnotationPolicy = {\n readOnly: true,\n destructive: false,\n idempotent: true,\n openWorld: false,\n}\n\nconst NON_DESTRUCTIVE_MUTATION_ANNOTATION: ToolAnnotationPolicy = {\n readOnly: false,\n destructive: false,\n idempotent: false,\n openWorld: false,\n}\n\nconst NON_DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION: ToolAnnotationPolicy = {\n readOnly: false,\n destructive: false,\n idempotent: true,\n openWorld: false,\n}\n\nconst DESTRUCTIVE_NON_IDEMPOTENT_MUTATION_ANNOTATION: ToolAnnotationPolicy = {\n readOnly: false,\n destructive: true,\n idempotent: false,\n openWorld: false,\n}\n\nconst DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION: ToolAnnotationPolicy = {\n readOnly: false,\n destructive: true,\n idempotent: true,\n openWorld: false,\n}\n\nconst REASON_IDEMPOTENT_DESTRUCTIVE_UPDATE =\n 'Update operations mutate persisted state but converge to the same end state under repeated identical input.'\n\nconst REASON_CART_EPHEMERAL =\n 'Cart is pre-checkout ephemeral state; reversal is possible by reissuing the prior input. Console enforces tenant scope.'\n\n/**\n * Generic collection write tool names that MUST NOT be registered.\n * Used by the inventory test (and any future allowlist guard) to prove these\n * never re-appear; runtime checks against an unknown tool name return\n * `tool_policy_missing` via {@link evaluateToolPolicy}.\n */\nexport const GENERIC_WRITE_TOOL_NAMES: readonly string[] = [\n 'create-collection',\n 'update-collection',\n 'delete-collection',\n 'update-many-collection',\n 'delete-many-collection',\n]\n\nexport const TOOL_POLICY_MANIFEST: Readonly<\n Record<McpToolName, ToolPolicyEntry>\n> = {\n // ── Read-only collection / validation (mcp:read, tenant-viewer) ──\n 'query-collection': {\n category: 'read-only-collection',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'GET /api/{collection}',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'get-collection-by-id': {\n category: 'read-only-collection',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'GET /api/{collection}/{id}',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'get-order': {\n category: 'read-only-collection',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'GET /api/orders/{id}',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'stock-check': {\n category: 'read-only-collection',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'GET /api/products/{id}/stock',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'product-detail': {\n category: 'read-only-collection',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'GET /api/products/detail',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'product-upsert': {\n category: 'mutation-product',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'POST /api/products/upsert',\n annotationPolicy: DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n exemptionReason: REASON_IDEMPOTENT_DESTRUCTIVE_UPDATE,\n },\n 'validate-discount': {\n category: 'read-only-collection',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'POST /api/discounts/validate',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'calculate-shipping': {\n category: 'read-only-collection',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'POST /api/shipping/calculate',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'get-collection-schema': {\n category: 'read-only-collection',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'GET /api/tenants/schema/{collectionSlug}',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'list-configurable-fields': {\n category: 'read-only-collection',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'GET /api/tenants/field-config',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n\n // ── Tenant context (mcp:read, tenant-viewer) ──\n 'get-tenant-context': {\n category: 'read-only-tenant',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'GET /api/tenants/context',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'check-feature-progress': {\n category: 'read-only-tenant',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'GET /api/tenants/feature-progress',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n\n // ── Cart mutations (mcp:write, tenant-editor) ──\n 'add-cart-item': {\n category: 'mutation-cart',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-editor',\n consoleSurface: 'POST /api/carts/{id}/items',\n annotationPolicy: NON_DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n },\n 'update-cart-item': {\n category: 'mutation-cart',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-editor',\n consoleSurface: 'PATCH /api/carts/{id}/items/{itemId}',\n annotationPolicy: DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n exemptionReason: REASON_CART_EPHEMERAL,\n },\n 'remove-cart-item': {\n category: 'mutation-cart',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-editor',\n consoleSurface: 'DELETE /api/carts/{id}/items/{itemId}',\n annotationPolicy: DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n exemptionReason: REASON_CART_EPHEMERAL,\n },\n 'clear-cart': {\n category: 'mutation-cart',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-editor',\n consoleSurface: 'POST /api/carts/{id}/clear',\n annotationPolicy: DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n exemptionReason: REASON_CART_EPHEMERAL,\n },\n 'apply-discount': {\n category: 'mutation-cart',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-editor',\n consoleSurface: 'POST /api/carts/{id}/discount',\n annotationPolicy: DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n exemptionReason: REASON_CART_EPHEMERAL,\n },\n 'remove-discount': {\n category: 'mutation-cart',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-editor',\n consoleSurface: 'DELETE /api/carts/{id}/discount',\n annotationPolicy: DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n exemptionReason: REASON_CART_EPHEMERAL,\n },\n\n // ── Order mutations (mcp:write, tenant-admin) ──\n checkout: {\n category: 'mutation-order',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'POST /api/checkout',\n annotationPolicy: DESTRUCTIVE_NON_IDEMPOTENT_MUTATION_ANNOTATION,\n },\n 'create-order': {\n category: 'mutation-order',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'POST /api/orders',\n annotationPolicy: DESTRUCTIVE_NON_IDEMPOTENT_MUTATION_ANNOTATION,\n },\n 'update-order': {\n category: 'mutation-order',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'PATCH /api/orders/{id}',\n annotationPolicy: DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n exemptionReason: REASON_IDEMPOTENT_DESTRUCTIVE_UPDATE,\n },\n\n // ── Fulfillment mutations (mcp:write, tenant-admin) ──\n 'create-fulfillment': {\n category: 'mutation-fulfillment',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'POST /api/orders/{id}/fulfillments',\n annotationPolicy: NON_DESTRUCTIVE_MUTATION_ANNOTATION,\n },\n 'update-fulfillment': {\n category: 'mutation-fulfillment',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'PATCH /api/fulfillments/{id}',\n annotationPolicy: DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n exemptionReason: REASON_IDEMPOTENT_DESTRUCTIVE_UPDATE,\n },\n\n // ── Return mutations (mcp:write, tenant-admin) ──\n 'create-return': {\n category: 'mutation-return',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'POST /api/returns',\n annotationPolicy: DESTRUCTIVE_NON_IDEMPOTENT_MUTATION_ANNOTATION,\n },\n 'update-return': {\n category: 'mutation-return',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'PATCH /api/returns/{id}',\n annotationPolicy: DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n exemptionReason: REASON_IDEMPOTENT_DESTRUCTIVE_UPDATE,\n },\n 'return-with-refund': {\n category: 'mutation-return',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'POST /api/returns/with-refund',\n annotationPolicy: DESTRUCTIVE_NON_IDEMPOTENT_MUTATION_ANNOTATION,\n },\n\n // ── Transaction mutations (mcp:write, tenant-admin) ──\n 'update-transaction': {\n category: 'mutation-transaction',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'PATCH /api/transactions/{id}',\n annotationPolicy: DESTRUCTIVE_NON_IDEMPOTENT_MUTATION_ANNOTATION,\n },\n\n // ── Field-config mutations (mcp:write, tenant-admin) ──\n 'update-field-config': {\n category: 'mutation-field-config',\n oauthScope: MCP_SCOPES.write,\n consoleRole: 'tenant-admin',\n consoleSurface: 'PATCH /api/tenants/field-config',\n annotationPolicy: NON_DESTRUCTIVE_IDEMPOTENT_MUTATION_ANNOTATION,\n },\n\n // ── SDK doc tools (mcp:read, tenant-viewer, sdk-static surface) ──\n 'sdk-get-recipe': {\n category: 'sdk-doc',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'sdk-static',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'sdk-search-docs': {\n category: 'sdk-doc',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'sdk-static',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'sdk-get-auth-setup': {\n category: 'sdk-doc',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'sdk-static',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n 'sdk-get-collection-pattern': {\n category: 'sdk-doc',\n oauthScope: MCP_SCOPES.read,\n consoleRole: 'tenant-viewer',\n consoleSurface: 'sdk-static',\n annotationPolicy: READ_ONLY_ANNOTATION,\n },\n}\n\nexport type ToolPolicyDenialReason =\n | 'tool_policy_missing'\n | 'insufficient_scope'\n\nexport type ToolPolicyDecision =\n | { allowed: true; entry: ToolPolicyEntry }\n | { allowed: false; reason: ToolPolicyDenialReason; message: string }\n\nexport function evaluateToolPolicy(\n toolName: string,\n scopes: readonly ToolOAuthScope[],\n): ToolPolicyDecision {\n if (!isMcpToolName(toolName)) {\n return {\n allowed: false,\n reason: 'tool_policy_missing',\n message: `No tool-policy entry for ${toolName}`,\n }\n }\n const entry = TOOL_POLICY_MANIFEST[toolName]\n if (!scopes.includes(entry.oauthScope)) {\n return {\n allowed: false,\n reason: 'insufficient_scope',\n message: `Tool ${toolName} requires ${entry.oauthScope}`,\n }\n }\n return { allowed: true, entry }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\nimport { randomUUID } from 'node:crypto'\nimport {\n MCP_TOOL_CONTRACT,\n isMcpToolName,\n type McpToolName,\n type McpTransport,\n} from '@01.software/contracts'\nimport { consolePostTelemetry, resolveApiKey } from './console-api'\n\nconst TELEMETRY_ENDPOINT = '/api/tenants/mcp-telemetry'\nconst FLUSH_TIMEOUT_MS = 1_500\n\nexport interface McpTelemetrySummary {\n durationMs?: number\n sessionId: string\n startedAtMs: number\n successfulWriteCount: number\n toolCallCount: number\n toolCounts: Map<McpToolName, number>\n transport: McpTransport\n}\n\nexport interface McpTelemetryBody {\n converted: boolean\n durationMs?: number\n sessionId: string\n successfulWriteCount: number\n toolCallCount: number\n toolCounts: Record<string, number>\n transport: McpTransport\n}\n\nconst telemetryContext = new AsyncLocalStorage<McpTelemetrySummary>()\n\nexport function createMcpTelemetrySummary(\n transport: McpTransport,\n): McpTelemetrySummary {\n return {\n sessionId: randomUUID(),\n startedAtMs: Date.now(),\n successfulWriteCount: 0,\n toolCallCount: 0,\n toolCounts: new Map(),\n transport,\n }\n}\n\nexport function currentMcpTelemetrySummary(): McpTelemetrySummary | undefined {\n return telemetryContext.getStore()\n}\n\nexport function runWithMcpTelemetry<T>(\n summary: McpTelemetrySummary,\n fn: () => T,\n): T {\n return telemetryContext.run(summary, fn)\n}\n\nexport function recordMcpToolResult(params: {\n resultText: string | null\n summary: McpTelemetrySummary\n toolName: string\n}): void {\n if (!isMcpToolName(params.toolName)) return\n\n const toolName = params.toolName\n params.summary.toolCallCount += 1\n params.summary.toolCounts.set(\n toolName,\n (params.summary.toolCounts.get(toolName) ?? 0) + 1,\n )\n\n if (\n !MCP_TOOL_CONTRACT[toolName].readOnly &&\n toolResultSucceeded(params.resultText)\n ) {\n params.summary.successfulWriteCount += 1\n }\n}\n\nexport function toMcpTelemetryBody(\n summary: McpTelemetrySummary,\n): McpTelemetryBody | null {\n if (summary.toolCallCount <= 0) return null\n\n const durationMs =\n summary.transport === 'http'\n ? Math.max(0, summary.durationMs ?? Date.now() - summary.startedAtMs)\n : undefined\n\n return {\n converted: summary.successfulWriteCount > 0,\n ...(durationMs !== undefined ? { durationMs } : {}),\n sessionId: summary.sessionId,\n successfulWriteCount: summary.successfulWriteCount,\n toolCallCount: summary.toolCallCount,\n toolCounts: Object.fromEntries(summary.toolCounts),\n transport: summary.transport,\n }\n}\n\nexport async function flushMcpTelemetrySummary(\n summary: McpTelemetrySummary,\n): Promise<void> {\n const body = toMcpTelemetryBody(summary)\n if (!body) return\n\n await swallow(\n withTimeout(async () => {\n const apiKey = resolveApiKey()\n await consolePostTelemetry(TELEMETRY_ENDPOINT, body, apiKey)\n }, FLUSH_TIMEOUT_MS),\n )\n}\n\nfunction toolResultSucceeded(resultText: string | null): boolean {\n if (!resultText) return false\n try {\n const parsed = JSON.parse(resultText) as { success?: unknown }\n return parsed.success === true\n } catch {\n return false\n }\n}\n\nasync function withTimeout(\n fn: () => Promise<void>,\n timeoutMs: number,\n): Promise<void> {\n let timer: NodeJS.Timeout | undefined\n await Promise.race([\n fn(),\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, timeoutMs)\n }),\n ])\n if (timer) clearTimeout(timer)\n}\n\nasync function swallow(promise: Promise<void>): Promise<void> {\n try {\n await promise\n } catch {\n // Telemetry must never fail tool execution or the HTTP response lifecycle.\n }\n}\n","/**\n * Console API 호출 공유 유틸리티\n *\n * tenant-context.ts와 field-config.ts가 공유하는 로직:\n * stdio credential 해석, auth 헤더 생성, 타임아웃, 에러 추출.\n * HTTP MCP 요청은 tenant-bound service JWT로 Console 호출을 만든다.\n */\n\nimport { createHash } from 'node:crypto'\nimport { hasRequestContext, tenantAuthContext } from './request-context'\nimport { signMcpServiceToken } from '../service-auth'\n\nconst DEFAULT_API_URL = 'https://api.01.software'\nconst TIMEOUT_MS = 5_000\nconst MISSING_HTTP_AUTH_CONTEXT_ERROR =\n 'MCP HTTP requests require a validated OAuth tenant context before tool execution.'\n\ninterface AuthHeaderContext {\n apiKey?: string\n mode: 'oauth' | 'stdio'\n publishableKey?: string\n}\n\nexport function resolveConsoleApiUrl(): string {\n return (\n process.env.SOFTWARE_API_URL ||\n process.env.NEXT_PUBLIC_SOFTWARE_API_URL ||\n DEFAULT_API_URL\n ).replace(/\\/$/, '')\n}\n\nfunction resolveAuthHeaderContext(): AuthHeaderContext {\n const oauthContext = tenantAuthContext()\n if (oauthContext) {\n return {\n apiKey: signMcpServiceToken(oauthContext),\n mode: 'oauth',\n }\n }\n if (hasRequestContext()) throw new Error(MISSING_HTTP_AUTH_CONTEXT_ERROR)\n\n return {\n apiKey: process.env.SOFTWARE_SECRET_KEY,\n mode: 'stdio',\n publishableKey:\n process.env.SOFTWARE_PUBLISHABLE_KEY ??\n process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY,\n }\n}\n\n/**\n * 현재 전송 모드에 맞는 downstream bearer 토큰을 해석한다.\n * - HTTP OAuth: tenant-bound service JWT\n * - stdio: SOFTWARE_SECRET_KEY\n */\nexport function resolveApiKey(): string {\n const { apiKey } = resolveAuthHeaderContext()\n if (!apiKey || typeof apiKey !== 'string') {\n throw new Error(\n 'Authentication required. Set SOFTWARE_SECRET_KEY for stdio transport.',\n )\n }\n return apiKey\n}\n\n/** SHA-256 해시로 캐시 키 생성 (시크릿을 메모리에 평문 저장하지 않기 위함) */\nexport function hashKey(apiKey: string): string {\n return createHash('sha256').update(apiKey).digest('hex')\n}\n\n/**\n * Build a cache key for auth-scoped data without storing raw credentials.\n * Include publishable key because tenant routing participates in SDK auth.\n */\nexport function resolveAuthCacheKey(apiKey: string): string {\n const oauthContext = tenantAuthContext()\n if (oauthContext) {\n return hashKey(\n JSON.stringify({\n mode: 'oauth',\n principalId: oauthContext.principalId ?? '',\n scopes: oauthContext.scopes,\n tenantId: oauthContext.tenantId,\n }),\n )\n }\n const { publishableKey } = resolveAuthHeaderContext()\n return hashKey(\n JSON.stringify({\n apiKey,\n publishableKey: publishableKey ?? '',\n }),\n )\n}\n\n/** Console validateAuthHeaders가 기대하는 인증 헤더 생성 */\nfunction buildAuthHeaders(apiKey: string): Record<string, string> {\n const { mode, publishableKey } = resolveAuthHeaderContext()\n const headers: Record<string, string> = {\n Authorization: `Bearer ${apiKey}`,\n }\n if (mode === 'stdio' && publishableKey) {\n headers['X-Publishable-Key'] = publishableKey\n }\n return headers\n}\n\n/**\n * Console 응답에서 에러 메시지를 추출한다.\n * 3가지 형식 대응:\n * - validateAuthHeaders: { error: \"message\" }\n * - Payload REST: { errors: [{ message }] }\n * - Simple: { message }\n */\nfunction extractErrorMessage(body: unknown): string | undefined {\n if (!body || typeof body !== 'object') return undefined\n const b = body as Record<string, unknown>\n // validateAuthHeaders error format: { error: \"Client key is required\" }\n if (typeof b.error === 'string') return b.error\n // Payload REST error format: { errors: [{ message }] }\n if (Array.isArray(b.errors) && b.errors[0]?.message) {\n return String(b.errors[0].message)\n }\n // Simple { message } format\n if (typeof b.message === 'string') return b.message\n return undefined\n}\n\n/** Console GET 엔드포인트 호출 (5s 타임아웃) */\nexport async function consoleGet<T = unknown>(\n path: string,\n apiKey: string,\n): Promise<T> {\n const authHeaders = buildAuthHeaders(apiKey)\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS)\n\n try {\n const res = await fetch(`${resolveConsoleApiUrl()}${path}`, {\n headers: authHeaders,\n signal: controller.signal,\n })\n if (!res.ok) {\n const body = await res.json().catch(() => ({}))\n const msg = extractErrorMessage(body)\n throw new Error(msg || `Console GET ${path} failed: ${res.status}`)\n }\n return res.json() as Promise<T>\n } finally {\n clearTimeout(timeoutId)\n }\n}\n\n/** Console POST 엔드포인트 호출 (5s 타임아웃) */\nexport async function consolePost<T = unknown>(\n path: string,\n body: unknown,\n apiKey: string,\n): Promise<T> {\n const authHeaders = buildAuthHeaders(apiKey)\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS)\n\n try {\n const res = await fetch(`${resolveConsoleApiUrl()}${path}`, {\n method: 'POST',\n headers: { ...authHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal: controller.signal,\n })\n if (!res.ok) {\n const errBody = await res.json().catch(() => ({}))\n const msg = extractErrorMessage(errBody)\n throw new Error(msg || `Console POST ${path} failed: ${res.status}`)\n }\n return res.json() as Promise<T>\n } finally {\n clearTimeout(timeoutId)\n }\n}\n\n/** Console telemetry POST endpoint 호출.\n * 204/202/empty responses are success; callers should fail-open around this.\n */\nexport async function consolePostTelemetry(\n path: string,\n body: unknown,\n apiKey: string,\n): Promise<void> {\n const authHeaders = buildAuthHeaders(apiKey)\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), TIMEOUT_MS)\n\n try {\n const res = await fetch(`${resolveConsoleApiUrl()}${path}`, {\n method: 'POST',\n headers: { ...authHeaders, 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n signal: controller.signal,\n })\n if (!res.ok) {\n const errBody = await res.json().catch(() => ({}))\n const msg = extractErrorMessage(errBody)\n throw new Error(msg || `Console POST ${path} failed: ${res.status}`)\n }\n } finally {\n clearTimeout(timeoutId)\n }\n}\n","import { createPrivateKey, randomUUID, sign as signBytes } from 'node:crypto'\nimport {\n MCP_CONSOLE_SERVICE_AUDIENCE,\n MCP_CONSOLE_SERVICE_SCOPE,\n MCP_OAUTH_ISSUER,\n MCP_SERVICE_TOKEN_LIFETIME_SECONDS,\n MCP_TENANT_CLAIM,\n MCP_TENANT_ROLE_CLAIM,\n} from '@01.software/auth-contracts'\nimport type { TenantAuthContext } from './auth'\n\ntype Jwk = Record<string, unknown>\nconst KEYSET_ENV = 'MCP_SERVICE_KEYSET'\n\nfunction assertProductionKeysetUse(source: string): void {\n const vercelEnv = process.env.VERCEL_ENV\n if (vercelEnv && vercelEnv !== 'production') {\n throw new Error(\n `${source} is only allowed in production Vercel deployments; non-production MCP service auth needs environment-specific issuer, audience, JWKS URI, and key material`,\n )\n }\n}\n\nfunction parsePrivateJwk(): Jwk {\n const keyset = signingKeyset()\n const jwk = keyset.current\n const source = keyset.source\n if (typeof jwk.d !== 'string' || jwk.d.length === 0) {\n throw new Error(`${source} current key must be a private JWK`)\n }\n if (typeof jwk.kid !== 'string' || jwk.kid.length === 0) {\n throw new Error(`${source} must include kid`)\n }\n return jwk\n}\n\nfunction signingKeyset(): { current: Jwk; keys: Jwk[]; source: string } {\n const raw = process.env[KEYSET_ENV]\n const source = KEYSET_ENV\n if (raw) assertProductionKeysetUse(source)\n const parsed = (() => {\n if (!raw) return null\n try {\n return JSON.parse(raw) as unknown\n } catch {\n throw new Error(`${KEYSET_ENV} is invalid JSON`)\n }\n })()\n if (!parsed) throw new Error('MCP service JWT signing key is not configured')\n\n const keys = Array.isArray((parsed as { keys?: unknown }).keys)\n ? ((parsed as { keys: Jwk[] }).keys)\n : [parsed as Jwk]\n if (keys.length === 0 || keys.length > 2) {\n throw new Error(\n `${source} must contain one current key and at most one previous key`,\n )\n }\n\n const currentKid = (parsed as { current_kid?: unknown }).current_kid\n if (typeof currentKid !== 'string' && keys.length > 1) {\n throw new Error(\n `${source} must include current_kid when multiple keys are present`,\n )\n }\n const current =\n typeof currentKid === 'string'\n ? keys.find((key) => key.kid === currentKid)\n : keys[0]\n if (!current) throw new Error(`${source} current_kid is not in keys`)\n return { current, keys, source }\n}\n\nfunction algForJwk(jwk: Jwk): 'RS256' | 'ES256' {\n if (jwk.kty === 'RSA') return 'RS256'\n if (jwk.kty === 'EC' && jwk.crv === 'P-256') return 'ES256'\n throw new Error('MCP service JWT signing key must be RSA or P-256 EC')\n}\n\nfunction toPublicJwk(jwk: Jwk): Jwk {\n const {\n d: _d,\n p: _p,\n q: _q,\n dp: _dp,\n dq: _dq,\n qi: _qi,\n oth: _oth,\n ...publicJwk\n } = jwk\n return {\n ...publicJwk,\n alg: typeof publicJwk.alg === 'string' ? publicJwk.alg : algForJwk(jwk),\n use: 'sig',\n }\n}\n\nfunction base64urlJson(value: unknown): string {\n return Buffer.from(JSON.stringify(value)).toString('base64url')\n}\n\nfunction apiScopesFor(context: TenantAuthContext): Array<'read' | 'write'> {\n return context.scopes.includes('mcp:write') ? ['read', 'write'] : ['read']\n}\n\nexport function mcpServicePublicJwks(): { keys: Jwk[] } {\n const keyset = signingKeyset()\n const keys = new Map<string, Jwk>()\n for (const jwk of keyset.keys.map(toPublicJwk)) {\n if (typeof jwk.kid === 'string' && jwk.kid.length > 0) {\n keys.set(jwk.kid, jwk)\n }\n }\n return { keys: [...keys.values()] }\n}\n\nexport function signMcpServiceToken(context: TenantAuthContext): string {\n if (!context.principalId) {\n throw new Error('MCP OAuth principal is required for Console service auth')\n }\n\n const jwk = parsePrivateJwk()\n const alg = algForJwk(jwk)\n const now = Math.floor(Date.now() / 1000)\n const payload = {\n iss: MCP_OAUTH_ISSUER,\n aud: MCP_CONSOLE_SERVICE_AUDIENCE,\n iat: now,\n nbf: now,\n exp: now + MCP_SERVICE_TOKEN_LIFETIME_SECONDS,\n jti: randomUUID(),\n sub: context.principalId,\n act: {\n sub: context.principalId,\n tenant_id: context.tenantId,\n },\n [MCP_TENANT_CLAIM]: context.tenantId,\n [MCP_TENANT_ROLE_CLAIM]: context.tenantRole,\n scope: MCP_CONSOLE_SERVICE_SCOPE,\n api_scopes: apiScopesFor(context),\n mcp_scopes: context.scopes,\n }\n const header = { alg, kid: jwk.kid, typ: 'JWT' }\n const encodedHeader = base64urlJson(header)\n const encodedPayload = base64urlJson(payload)\n const signingInput = `${encodedHeader}.${encodedPayload}`\n const key = createPrivateKey({ key: jwk, format: 'jwk' })\n const signature =\n alg === 'RS256'\n ? signBytes('RSA-SHA256', Buffer.from(signingInput), key)\n : signBytes('SHA256', Buffer.from(signingInput), {\n key,\n dsaEncoding: 'ieee-p1363',\n })\n return `${signingInput}.${signature.toString('base64url')}`\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { SERVER_COLLECTIONS } from '@01.software/sdk'\nimport { toolSuccess, toolError, parseJsonWhere } from '../lib/tool-utils'\n\nexport const schema = {\n collection: z.enum(SERVER_COLLECTIONS).describe('Collection name (required)'),\n where: z\n .string()\n .optional()\n .describe(\n 'Filter conditions (JSON string, optional). Pass the Payload query condition object as a JSON string. Example: \\'{\"title\":{\"equals\":\"Product name\"}}\\'',\n ),\n limit: z\n .number()\n .min(1)\n .max(100)\n .default(10)\n .describe('Maximum number of items to return (1-100, default: 10).'),\n page: z\n .number()\n .optional()\n .describe('Page number (optional). Starts from 1. Used for pagination.'),\n sort: z\n .string()\n .regex(\n /^-?[a-zA-Z0-9_.]+$/,\n 'Sort must be a field name, optionally prefixed with \"-\" for descending',\n )\n .optional()\n .describe(\n 'Sort field (optional). Use \"fieldName\" for ascending or \"-fieldName\" for descending. Example: \"createdAt\" or \"-createdAt\"',\n ),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'query-collection',\n description:\n 'Query collection data. Supports filtering, sorting, and pagination.',\n annotations: {\n title: 'Query collection',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function queryCollection({\n collection,\n where,\n limit,\n page,\n sort,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let parsedWhere: any\n if (where) {\n const parsed = parseJsonWhere(where)\n if (!parsed.success) return parsed.error\n parsedWhere = parsed.data\n }\n\n const result = await client.collections.from(collection).find({\n where: parsedWhere,\n limit,\n page,\n sort,\n })\n\n return toolSuccess({\n data: result.docs,\n pagination: {\n page: result.page,\n limit: result.limit,\n totalDocs: result.totalDocs,\n totalPages: result.totalPages,\n hasNextPage: result.hasNextPage,\n hasPrevPage: result.hasPrevPage,\n prevPage: result.prevPage,\n nextPage: result.nextPage,\n },\n })\n } catch (error) {\n return toolError(error)\n }\n}\n","/**\n * SDK 클라이언트 인스턴스 관리\n *\n * Stdio transport uses local env credentials. HTTP MCP OAuth requests use a\n * tenant-bound service JWT for downstream Console calls.\n *\n * 환경 변수:\n * - SOFTWARE_SECRET_KEY: stdio 전송 시 raw bearer 토큰\n * - SOFTWARE_PUBLISHABLE_KEY: publishable key\n * - SOFTWARE_API_URL: API 기본 URL (선택)\n */\n\nimport { hasRequestContext, tenantAuthContext } from './request-context'\nimport { createServerClient } from '@01.software/sdk'\n\nconst MISSING_HTTP_AUTH_CONTEXT_ERROR =\n 'MCP HTTP requests require a validated OAuth tenant context before tool execution.'\nconst HTTP_OAUTH_SDK_CLIENT_ERROR =\n 'MCP HTTP OAuth requests cannot use SDK-backed tools. Use reviewed Console service endpoints for OAuth transport.'\n\n/**\n * SDK-compatible server client instance를 생성합니다.\n * HTTP OAuth 요청은 service JWT, stdio 요청은 SOFTWARE_SECRET_KEY를 사용합니다.\n *\n * @returns ServerClient 인스턴스\n * @throws Error if authentication is missing or invalid\n */\nexport function getClient() {\n const oauthContext = tenantAuthContext()\n if (oauthContext) {\n throw new Error(HTTP_OAUTH_SDK_CLIENT_ERROR)\n }\n if (hasRequestContext()) throw new Error(MISSING_HTTP_AUTH_CONTEXT_ERROR)\n\n const secretKey = process.env.SOFTWARE_SECRET_KEY\n const publishableKey =\n process.env.SOFTWARE_PUBLISHABLE_KEY ||\n process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY\n\n if (!secretKey) {\n throw new Error(\n 'Authentication required. Set SOFTWARE_SECRET_KEY for stdio transport.',\n )\n }\n\n if (!secretKey.startsWith('sk01_') && !secretKey.startsWith('pat01_')) {\n throw new Error('Invalid SOFTWARE_SECRET_KEY format. Expected sk01_ or pat01_ token.')\n }\n\n if (!publishableKey) {\n throw new Error(\n 'publishableKey is required. Set SOFTWARE_PUBLISHABLE_KEY for stdio transport. ' +\n 'It is used for rate limiting and monthly quota enforcement via the edge proxy.',\n )\n }\n\n return createServerClient({\n publishableKey,\n secretKey,\n })\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { SERVER_COLLECTIONS } from '@01.software/sdk'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n collection: z.enum(SERVER_COLLECTIONS).describe('Collection name (required)'),\n id: z.string().min(1).describe('Item ID (required)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'get-collection-by-id',\n description: 'Get a specific collection item by ID',\n annotations: {\n title: 'Get collection item by ID',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function getCollectionById({\n collection,\n id,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient().collections\n\n const result = await client.from(collection).findById(id)\n\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n orderNumber: z.string().min(1).describe('Order number to look up (required)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'get-order',\n description:\n 'Get order details by order number. Returns order with related data (depth:1).',\n annotations: {\n title: 'Get order by number',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function getOrder({\n orderNumber,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const { docs } = await client.collections.from('orders').find({\n where: { orderNumber: { equals: orderNumber } },\n limit: 1,\n depth: 1,\n })\n const result = docs[0] ?? null\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n pgPaymentId: z\n .string()\n .optional()\n .describe('PG payment ID (optional — omit for free orders)'),\n orderNumber: z.string().min(1).describe('Unique order number (required)'),\n customerSnapshot: z\n .object({\n name: z.string().optional().describe('Customer name'),\n email: z.string().describe('Customer email (required)'),\n phone: z.string().optional().describe('Customer phone'),\n })\n .describe('Customer snapshot at time of order (required)'),\n shippingAddress: z\n .record(z.string(), z.unknown())\n .describe(\n 'Shipping address object (required). Fields: postalCode, address1, address2, deliveryMessage, recipientName, phone',\n ),\n orderItems: z\n .array(z.record(z.string(), z.unknown()))\n .describe(\n 'Array of order item objects (required). Each: { product, variant, option, quantity, unitPrice?, totalPrice? }',\n ),\n totalAmount: z.number().nonnegative().describe('Total order amount (required, min 0)'),\n shippingAmount: z\n .number()\n .nonnegative()\n .optional()\n .describe('Shipping amount (optional, default 0)'),\n discountCode: z\n .string()\n .optional()\n .describe('Discount code to apply (optional)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'create-order',\n description:\n 'Create a new order with products and shipping information. Supports idempotency.',\n annotations: {\n title: 'Create order',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n },\n}\n\nexport default async function createOrder(params: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.orders.create(\n params as unknown as Parameters<typeof client.commerce.orders.create>[0],\n )\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n orderNumber: z.string().min(1).describe('Order number (required)'),\n status: z\n .enum([\n 'pending',\n 'paid',\n 'failed',\n 'canceled',\n 'preparing',\n 'shipped',\n 'delivered',\n 'confirmed',\n ])\n .describe(\n 'New order status. Return-related statuses (return_requested, return_processing, returned) must be set via Return endpoints.',\n ),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'update-order',\n description:\n 'Update order status. Automatically adjusts stock on status changes (e.g., canceled restores stock).',\n annotations: {\n title: 'Update order status',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n}\n\nexport default async function updateOrder({\n orderNumber,\n status,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.orders.update({ orderNumber, status })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n cartId: z.string().min(1).describe('Cart ID to convert to order (required)'),\n pgPaymentId: z\n .string()\n .optional()\n .describe('PG payment ID (optional — omit for free orders)'),\n orderNumber: z.string().min(1).describe('Unique order number (required)'),\n customerSnapshot: z\n .record(z.string(), z.unknown())\n .describe(\n 'Customer snapshot object (required). Fields: { name?, email, phone? }',\n ),\n discountCode: z\n .string()\n .optional()\n .describe('Discount code to apply (optional)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'checkout',\n description:\n 'Convert a cart to an order. Validates stock, creates order and transaction, marks cart as completed. Supports idempotency.',\n annotations: {\n title: 'Checkout (cart to order)',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n },\n}\n\nexport default async function checkout(params: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.orders.checkout(\n params as unknown as Parameters<typeof client.commerce.orders.checkout>[0],\n )\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n orderNumber: z.string().min(1).describe('Order number (required)'),\n carrier: z.string().optional().describe('Shipping carrier name (optional)'),\n trackingNumber: z\n .string()\n .optional()\n .describe(\n 'Tracking number (optional). Setting carrier + tracking triggers \"shipped\" status',\n ),\n items: z\n .array(\n z.object({\n orderItem: z.string().min(1).describe('Order item ID'),\n quantity: z.number().int().positive().describe('Quantity to fulfill'),\n }),\n )\n .describe('Array of items to fulfill (required)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'create-fulfillment',\n description:\n 'Create a shipment/fulfillment for order items. Auto-updates order status (paid → preparing → shipped).',\n annotations: {\n title: 'Create fulfillment',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n },\n}\n\nexport default async function createFulfillment({\n orderNumber,\n carrier,\n trackingNumber,\n items,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.orders.createFulfillment({\n orderNumber,\n carrier,\n trackingNumber,\n items,\n })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n fulfillmentId: z.string().min(1).describe('Fulfillment ID (required)'),\n status: z\n .enum(['packed', 'shipped', 'delivered', 'failed'])\n .describe(\n 'New fulfillment status (required). FSM: pending→packed/shipped/failed, packed→shipped/failed, shipped→delivered/failed',\n ),\n carrier: z\n .string()\n .optional()\n .describe(\n 'Shipping carrier (optional, changeable only in pending/packed status)',\n ),\n trackingNumber: z\n .string()\n .optional()\n .describe(\n 'Tracking number (optional, changeable only in pending/packed status)',\n ),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'update-fulfillment',\n description:\n 'Update fulfillment status, carrier, and tracking number. Auto-updates order status when all fulfillments are delivered.',\n annotations: {\n title: 'Update fulfillment',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n}\n\nexport default async function updateFulfillment({\n fulfillmentId,\n status,\n carrier,\n trackingNumber,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.orders.updateFulfillment({\n fulfillmentId,\n status,\n carrier,\n trackingNumber,\n })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { UpdateTransactionSchema } from '@01.software/contracts'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = UpdateTransactionSchema.shape\n\nexport const metadata: ToolMetadata = {\n name: 'update-transaction',\n description: 'Update transaction status, payment method, and receipt URL.',\n annotations: {\n title: 'Update transaction',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n },\n}\n\nexport default async function updateTransaction({\n pgPaymentId,\n status,\n paymentMethod,\n receiptUrl,\n paymentKey,\n amount,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const params = {\n pgPaymentId,\n status,\n paymentMethod,\n receiptUrl,\n paymentKey,\n amount,\n }\n const result = await client.commerce.orders.updateTransaction(params)\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n orderNumber: z.string().min(1).describe('Order number (required)'),\n reason: z\n .enum(['change_of_mind', 'defective', 'wrong_delivery', 'damaged', 'other'])\n .optional()\n .describe('Return reason (optional)'),\n reasonDetail: z\n .string()\n .optional()\n .describe('Detailed reason text (optional)'),\n returnItems: z\n .array(\n z.object({\n orderItem: z.string().min(1).describe('Order item ID'),\n quantity: z.number().int().positive().describe('Quantity to return'),\n }),\n )\n .describe('Array of products to return (required)'),\n refundAmount: z.number().nonnegative().describe('Refund amount (required, min 0)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'create-return',\n description:\n 'Create a return request for an order. Only works for delivered/confirmed orders. Updates order status to return_requested.',\n annotations: {\n title: 'Create return request',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n },\n}\n\nexport default async function createReturn({\n orderNumber,\n reason,\n reasonDetail,\n returnItems,\n refundAmount,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.orders.createReturn({\n orderNumber,\n reason,\n reasonDetail,\n returnItems,\n refundAmount,\n })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n returnId: z.string().min(1).describe('Return ID (required)'),\n status: z\n .enum(['processing', 'approved', 'rejected', 'completed'])\n .describe(\n 'New return status (required). Valid transitions: requested→processing/rejected, processing→approved/rejected, approved→completed',\n ),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'update-return',\n description:\n 'Update return status with FSM validation. Restores inventory on completion, reverts order status on rejection.',\n annotations: {\n title: 'Update return status',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n}\n\nexport default async function updateReturn({\n returnId,\n status,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.orders.updateReturn({ returnId, status })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { ReturnWithRefundSchema } from '@01.software/contracts'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = ReturnWithRefundSchema.shape\n\nexport const metadata: ToolMetadata = {\n name: 'return-with-refund',\n description:\n 'Combined return + refund operation. Creates return, restores stock, cancels transaction, updates order status.',\n annotations: {\n title: 'Return with refund',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n },\n}\n\nexport default async function returnWithRefund({\n orderNumber,\n reason,\n reasonDetail,\n returnItems,\n refundAmount,\n pgPaymentId,\n paymentKey,\n refundReceiptUrl,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const params = {\n orderNumber,\n reason,\n reasonDetail,\n returnItems,\n refundAmount,\n pgPaymentId,\n paymentKey,\n refundReceiptUrl,\n }\n const result = await client.commerce.orders.returnWithRefund(params)\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n cartId: z.string().min(1).describe('Cart ID (required)'),\n product: z.string().min(1).describe('Product ID (required)'),\n variant: z.string().min(1).describe('Product variant ID (required)'),\n option: z.string().min(1).describe('Product option ID (required)'),\n quantity: z.number().int().positive().describe('Quantity to add (required, positive integer)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'add-cart-item',\n description:\n 'Add a product to cart. Validates stock, merges quantity if item already exists, recalculates totals.',\n annotations: {\n title: 'Add item to cart',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function addCartItem({\n cartId,\n product,\n variant,\n option,\n quantity,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.cart.addItem({\n cartId,\n product,\n variant,\n option,\n quantity,\n })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n cartItemId: z.string().min(1).describe('Cart item ID (required)'),\n quantity: z.number().int().positive().describe('New quantity (required, positive integer)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'update-cart-item',\n description:\n 'Update cart item quantity. Validates stock availability, recalculates cart totals.',\n annotations: {\n title: 'Update cart item',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n}\n\nexport default async function updateCartItem({\n cartItemId,\n quantity,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.cart.updateItem({ cartItemId, quantity })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n cartItemId: z.string().min(1).describe('Cart item ID to remove (required)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'remove-cart-item',\n description:\n 'Remove an item from cart. Recalculates cart totals after removal.',\n annotations: {\n title: 'Remove cart item',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n}\n\nexport default async function removeCartItem({\n cartItemId,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.cart.removeItem({ cartItemId })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n cartId: z.string().min(1).describe('Cart ID (required)'),\n discountCode: z.string().describe('Discount code to apply (required)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'apply-discount',\n description:\n 'Apply a discount code to a cart. Validates the code, updates cart totals, and sets free shipping if applicable.',\n annotations: {\n title: 'Apply discount to cart',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n}\n\nexport default async function applyDiscount({\n cartId,\n discountCode,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.cart.applyDiscount({ cartId, discountCode })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n cartId: z.string().min(1).describe('Cart ID (required)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'remove-discount',\n description:\n 'Remove the applied discount code from a cart and recalculate totals.',\n annotations: {\n title: 'Remove discount from cart',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n}\n\nexport default async function removeDiscount({\n cartId,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.cart.removeDiscount({ cartId })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n cartId: z.string().min(1).describe('Cart ID (required)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'clear-cart',\n description:\n 'Remove all items from a cart, reset discount and amounts. Shipping fee is preserved.',\n annotations: {\n title: 'Clear cart',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n },\n}\n\nexport default async function clearCart({\n cartId,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.cart.clear({ cartId })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n code: z.string().describe('Discount code to validate (required)'),\n orderAmount: z.number().describe('Order amount for validation (required)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'validate-discount',\n description:\n 'Validate a discount code. Checks active status, date range, usage limits, minimum order amount, and calculates discount.',\n annotations: {\n title: 'Validate discount code',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function validateDiscount({\n code,\n orderAmount,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.discounts.validate({\n code,\n orderAmount,\n })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n shippingPolicyId: z\n .string()\n .optional()\n .describe('Shipping policy ID (uses default policy if omitted)'),\n orderAmount: z.number().describe('Order amount for fee calculation (required)'),\n postalCode: z\n .string()\n .optional()\n .describe('Postal code for Jeju surcharge detection (63000-63644)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'calculate-shipping',\n description:\n 'Calculate shipping fee based on order amount and postal code. Supports free shipping threshold and Jeju surcharge.',\n annotations: {\n title: 'Calculate shipping fee',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function calculateShipping({\n shippingPolicyId,\n orderAmount,\n postalCode,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.shipping.calculate({\n shippingPolicyId,\n orderAmount,\n postalCode,\n })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n items: z\n .array(\n z.object({\n variantId: z.string().describe('Product variant ID'),\n quantity: z.number().int().positive().describe('Requested quantity'),\n }),\n )\n .describe(\n 'Array of items to check stock for (required, max 100). Each: { variantId, quantity }',\n ),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'stock-check',\n description:\n 'Batch check product option stock availability. Returns per-item availability and an allAvailable flag.',\n annotations: {\n title: 'Check stock availability',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function stockCheck({\n items,\n}: InferSchema<typeof schema>) {\n try {\n const client = getClient()\n const result = await client.commerce.product.stockCheck({ items })\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n slug: z\n .string()\n .optional()\n .describe('Product slug (one of slug or id required)'),\n id: z.string().optional().describe('Product id (one of slug or id required)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'product-detail',\n description:\n 'Fetch full product detail by slug or id. Returns one resolver-ready product with variants, option slugs, option value slugs/media, brand, categories, tags, images, videos, and listing rollup, or null if missing/unpublished/wrong tenant/feature disabled.',\n annotations: {\n title: 'Get product detail',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function productDetail({\n slug,\n id,\n}: InferSchema<typeof schema>) {\n try {\n if (Boolean(slug) === Boolean(id)) {\n return toolError(new Error('Provide exactly one of slug or id'))\n }\n const client = getClient()\n const params = slug ? { slug } : { id: id! }\n const result = await client.commerce.product.detail(params)\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getClient } from '../lib/client'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nconst optionValueSchema = z.object({\n id: z.string().optional().describe('Existing option-value ID for updates'),\n value: z.string().describe('Display label (e.g. Black, S)'),\n slug: z\n .string()\n .optional()\n .describe('Canonical value token used in variant maps and URLs'),\n swatchColor: z.string().nullable().optional(),\n thumbnail: z.string().nullable().optional(),\n images: z.array(z.string()).optional(),\n metadata: z.unknown().optional(),\n})\n\nconst optionSchema = z.object({\n id: z.string().optional().describe('Existing option ID for updates'),\n title: z.string().describe('Option name (e.g. Color, Size)'),\n slug: z\n .string()\n .optional()\n .describe('Canonical option token used in variant maps and URLs'),\n values: z.array(optionValueSchema).describe('Allowed option values'),\n})\n\nconst variantOptionValueSchema = z.object({\n valueSlug: z.string().optional(),\n valueId: z.string().optional(),\n value: z.string().optional(),\n})\n\nconst variantSchema = z.object({\n id: z.string().optional().describe('Existing variant ID for updates'),\n optionValues: z\n .union([\n z.record(z.string(), z.union([z.string(), variantOptionValueSchema])),\n z.array(z.string()),\n ])\n .optional()\n .describe(\n 'Option-value selection. Prefer canonical { optionSlug: valueSlug } maps. Object values may use { valueSlug, valueId, value }. Exact { OptionTitle: ValueLabel } maps remain compatibility-only and fail when labels are ambiguous. Arrays of option-value IDs are also accepted.',\n ),\n sku: z.string().nullable().optional(),\n title: z.string().nullable().optional(),\n price: z.number().nonnegative().describe('Selling price (KRW, min 0)'),\n compareAtPrice: z.number().nonnegative().nullable().optional(),\n stock: z.number().int().nonnegative().optional(),\n isUnlimited: z.boolean().optional(),\n weight: z.number().nonnegative().nullable().optional(),\n requiresShipping: z.boolean().optional(),\n barcode: z.string().nullable().optional(),\n externalId: z.string().nullable().optional(),\n isActive: z.boolean().optional(),\n thumbnail: z.string().nullable().optional(),\n images: z.array(z.string()).optional(),\n metadata: z.unknown().optional(),\n})\n\nexport const schema = {\n product: z\n .record(z.string(), z.unknown())\n .describe(\n 'Product fields. Include `id` to update an existing product; omit for create (then `title` is required).',\n ),\n options: z\n .array(optionSchema)\n .optional()\n .describe(\n 'Option definitions. Prefer explicit option slug and value slugs. Omitted options on an existing product are deleted (with their values).',\n ),\n variants: z\n .array(variantSchema)\n .optional()\n .describe(\n 'Variant rows. Prefer canonical { optionSlug: valueSlug } optionValues maps. Omitted variants on an existing product are deleted, unless referenced by an active cart or non-terminal order — those are soft-deactivated (isActive: false).',\n ),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'product-upsert',\n description:\n 'Atomically create or update a product together with its options, option-values, and variants in a single transaction. Mirrors Shopify productSet semantics. Any failure rolls back the entire write.',\n annotations: {\n title: 'Upsert product (atomic)',\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n}\n\nexport default async function productUpsert(\n params: InferSchema<typeof schema>,\n) {\n try {\n const client = getClient()\n const result = await client.commerce.product.upsert(\n params as unknown as Parameters<typeof client.commerce.product.upsert>[0],\n )\n return toolSuccess({ data: result })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { createCollectionSchemaToolInputSchema } from '@01.software/contracts'\nimport { SERVER_COLLECTIONS } from '@01.software/sdk'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getCollectionSchema } from '../lib/collection-schema'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema =\n createCollectionSchemaToolInputSchema(SERVER_COLLECTIONS).shape\n\nexport const metadata: ToolMetadata = {\n name: 'get-collection-schema',\n description:\n 'Get the authoritative tenant-aware collection schema from console. Use this before create/update to understand writable fields, hidden fields, required metadata, and collection-level visibility.',\n annotations: {\n title: 'Get collection schema',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function getCollectionSchemaTool({\n collection,\n}: InferSchema<typeof schema>) {\n try {\n const result = await getCollectionSchema(collection)\n\n return toolSuccess({\n message: `Schema for '${collection}' (authoritative console contract)`,\n ...result,\n })\n } catch (error) {\n return toolError(error)\n }\n}\n","import {\n collectionSchemaResponseSchema,\n type CollectionFieldSchema,\n type CollectionSchemaResponse,\n} from '@01.software/contracts'\nimport { consoleGet, resolveApiKey } from './console-api'\n\nexport type { CollectionFieldSchema, CollectionSchemaResponse }\n\nexport async function getCollectionSchema(\n collection: string,\n): Promise<CollectionSchemaResponse> {\n const apiKey = resolveApiKey()\n\n const data = await consoleGet<unknown>(\n `/api/tenants/schema/${encodeURIComponent(collection)}`,\n apiKey,\n )\n\n return collectionSchemaResponseSchema.parse(data)\n}\n","/**\n * Tenant Context fetch 유틸\n *\n * Console /api/tenants/context 엔드포인트를 호출하여\n * 테넌트의 features, 활성 컬렉션, 필드 설정을 가져온다.\n */\n\nimport { resolveApiKey, consoleGet } from './console-api'\nimport {\n tenantContextResponseSchema,\n tenantFeatureProgressResponseSchema,\n type TenantFeatureProgressFeature,\n type TenantFeatureProgressResponse,\n type TenantContextResponse,\n} from '@01.software/contracts'\n\nfunction getTenantContextPath(includeCounts: boolean): string {\n return includeCounts\n ? '/api/tenants/context?counts=true'\n : '/api/tenants/context'\n}\n\nfunction getTenantFeatureProgressPath(\n feature: TenantFeatureProgressFeature,\n includeEvidence: boolean,\n): string {\n const search = new URLSearchParams({ feature })\n if (includeEvidence) search.set('includeEvidence', 'true')\n return `/api/tenants/feature-progress?${search.toString()}`\n}\n\nexport async function getTenantContext(\n includeCounts = false,\n): Promise<TenantContextResponse> {\n const apiKey = resolveApiKey()\n\n const data = await consoleGet<unknown>(\n getTenantContextPath(includeCounts),\n apiKey,\n )\n\n return tenantContextResponseSchema.parse(data)\n}\n\nexport async function getTenantFeatureProgress(\n feature: TenantFeatureProgressFeature,\n includeEvidence = false,\n): Promise<TenantFeatureProgressResponse> {\n const apiKey = resolveApiKey()\n\n const data = await consoleGet<unknown>(\n getTenantFeatureProgressPath(feature, includeEvidence),\n apiKey,\n )\n\n return tenantFeatureProgressResponseSchema.parse(data)\n}\n","import { tenantContextToolInputSchema } from '@01.software/contracts'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getTenantContext } from '../lib/tenant-context'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = tenantContextToolInputSchema.shape\n\nexport const metadata: ToolMetadata = {\n name: 'get-tenant-context',\n description:\n 'Get current tenant features, active collections, and field visibility. Call this at the start of every session. Use includeCounts=true to also get per-collection document counts for setup diagnostics.',\n annotations: {\n title: 'Get Tenant Context',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function handler({\n includeCounts,\n}: InferSchema<typeof schema>) {\n try {\n const ctx = await getTenantContext(includeCounts)\n\n const lines = [\n `# Tenant: ${ctx.tenant.name} (${ctx.tenant.plan} plan)`,\n '',\n '## Active Features',\n ...ctx.features.map((f) => `- ${f}`),\n '',\n `## Available Collections (${ctx.collections.active.length})`,\n ...ctx.collections.active.map((c) => `- ${c}`),\n '',\n '## Inactive Collections (do NOT use these)',\n ...ctx.collections.inactive.map((c) => `- ${c}`),\n ]\n\n // Hidden fields\n const hiddenEntries = Object.entries(ctx.fieldConfigs).filter(\n ([, v]) => v.hiddenFields.length > 0,\n )\n if (hiddenEntries.length > 0) {\n lines.push(\n '',\n '## Hidden Fields per Collection',\n 'Do not include these fields when generating code.',\n '',\n )\n for (const [slug, v] of hiddenEntries) {\n lines.push(`### ${slug}`, ...v.hiddenFields.map((f) => `- ${f}`))\n }\n }\n\n // Hidden collections (UI-level)\n const hiddenCollections = Object.entries(ctx.fieldConfigs)\n .filter(([, v]) => v.isHidden)\n .map(([slug]) => slug)\n if (hiddenCollections.length > 0) {\n lines.push(\n '',\n '## Hidden Collections (UI-hidden, avoid using)',\n ...hiddenCollections.map((c) => `- ${c}`),\n )\n }\n\n // Collection document counts\n if (ctx.counts) {\n lines.push(\n '',\n '## Collection Document Counts',\n 'Collections with 0 documents may need setup.',\n '',\n )\n for (const [slug, count] of Object.entries(ctx.counts)) {\n if (count === -1) {\n lines.push(`- ${slug}: (not available)`)\n } else {\n lines.push(`- ${slug}: ${count}`)\n }\n }\n }\n\n // Config status\n if (ctx.config) {\n lines.push('', '## Config Status')\n lines.push(\n `- Webhook configured: ${ctx.config.webhookConfigured ? 'Yes' : 'No'}`,\n )\n }\n\n return toolSuccess({ context: lines.join('\\n') })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { tenantFeatureProgressInputSchema } from '@01.software/contracts'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getTenantFeatureProgress } from '../lib/tenant-context'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = tenantFeatureProgressInputSchema.shape\n\nexport const metadata: ToolMetadata = {\n name: 'check-feature-progress',\n description:\n 'Check tenant implementation progress for a supported feature. Start with feature=ecommerce to inspect catalog, cart, checkout, payment result, webhook, and operations readiness without mutating tenant data.',\n annotations: {\n title: 'Check Feature Progress',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function handler({\n feature,\n includeEvidence,\n}: InferSchema<typeof schema>) {\n try {\n const progress = await getTenantFeatureProgress(feature, includeEvidence)\n return toolSuccess({ progress })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\nimport { fetchFieldConfigs } from '../lib/field-config'\n\nexport const schema = {\n collection: z\n .string()\n .optional()\n .describe(\n 'Filter by collection slug (optional — returns all if omitted). ' +\n 'Use this filter to reduce response size when you know which collection to check.',\n ),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'list-configurable-fields',\n description:\n 'List all configurable fields for tenant collections with current visibility state. ' +\n 'Shows which fields can be shown/hidden and their current status. ' +\n 'Returns all collections including inactive features — cross-reference with get-tenant-context for active features. ' +\n 'Response includes ~300 fields across 47 collections — use collection filter when possible.',\n annotations: {\n title: 'List configurable fields',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function listConfigurableFields(\n params: InferSchema<typeof schema>,\n) {\n try {\n const data = await fetchFieldConfigs()\n\n if (params.collection) {\n const entry = data[params.collection]\n if (!entry) {\n return toolError(\n new Error(\n `Collection '${params.collection}' is not configurable`,\n ),\n )\n }\n return toolSuccess({ data: { [params.collection]: entry } })\n }\n\n return toolSuccess({ data })\n } catch (error) {\n return toolError(error)\n }\n}\n","/**\n * Field Config API 호출 유틸리티\n *\n * Console /api/field-configs/* 엔드포인트를 호출하여\n * 테넌트별 필드 설정을 조회·수정한다.\n */\n\nimport {\n resolveApiKey,\n consoleGet,\n consolePost,\n} from './console-api'\n\n// --- 타입 ---\n\nexport interface ConfigurableFieldEntry {\n fields: Array<{\n path: string\n label: string\n hidden: boolean\n minPlan?: string\n }>\n isHidden: boolean\n}\n\ntype FieldConfigListResponse = Record<string, ConfigurableFieldEntry>\n\n/** Console GET /api/field-configs/list 호출 */\nexport async function fetchFieldConfigs(): Promise<FieldConfigListResponse> {\n const apiKey = resolveApiKey()\n\n const data = await consoleGet<FieldConfigListResponse>(\n '/api/field-configs/list',\n apiKey,\n )\n\n return data\n}\n\n/** Console POST /api/field-configs/save 호출 */\nexport async function saveFieldConfig(body: {\n collectionSlug: string\n hiddenFields: string[]\n isHidden?: boolean\n}): Promise<Record<string, unknown>> {\n const apiKey = resolveApiKey()\n return consolePost<Record<string, unknown>>(\n '/api/field-configs/save',\n body,\n apiKey,\n )\n}\n\n/** Compatibility no-op: capability-bearing MCP responses are not cached locally. */\nexport function invalidateFieldConfigCache() {\n // Intentionally empty.\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\nimport {\n saveFieldConfig,\n invalidateFieldConfigCache,\n} from '../lib/field-config'\n\nexport const schema = {\n collection: z.string().min(1).describe('Collection slug (required)'),\n hiddenFields: z\n .array(z.string().min(1).max(200))\n .max(300)\n .describe(\n 'Fields to hide (required). This is a FULL REPLACE — fields NOT in this list will be shown. ' +\n 'Pass [] to show all fields. Use list-configurable-fields first to see available field paths.',\n ),\n isHidden: z\n .boolean()\n .optional()\n .describe(\n 'Hide the entire collection from Admin Panel (optional). ' +\n 'When true, individual hiddenFields are irrelevant.',\n ),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'update-field-config',\n description:\n 'Update field visibility configuration for a tenant collection. ' +\n 'Hidden fields are removed from the Admin Panel UI. ' +\n 'IMPORTANT: hiddenFields is a full replace, not a merge. ' +\n 'Always call list-configurable-fields first to see current state.',\n annotations: {\n title: 'Update field config',\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default async function updateFieldConfig(\n params: InferSchema<typeof schema>,\n) {\n try {\n const result = await saveFieldConfig({\n collectionSlug: params.collection,\n hiddenFields: params.hiddenFields,\n isHidden: params.isHidden,\n })\n\n invalidateFieldConfigCache()\n\n return toolSuccess({\n message: `Field config updated for '${params.collection}'`,\n data: result,\n })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { getRecipe } from '../lib/sdk-recipes'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n goal: z\n .enum([\n 'fetch-list',\n 'fetch-by-id',\n 'create-item',\n 'update-item',\n 'delete-item',\n 'infinite-scroll',\n 'ssr-prefetch',\n 'customer-auth',\n 'file-upload',\n 'bulk-operations',\n ])\n .describe('What the user wants to accomplish'),\n runtime: z\n .enum(['browser', 'server', 'both'])\n .default('both')\n .describe('Target runtime environment'),\n collection: z\n .string()\n .optional()\n .describe('Specific collection name if applicable'),\n includeExample: z\n .boolean()\n .default(true)\n .describe('Whether to include a full code example'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'sdk-get-recipe',\n description:\n 'Get a complete SDK code recipe for a specific task. Returns recommended approach, code example, and related documentation links. Use this FIRST when the user asks how to do something with the SDK.',\n annotations: {\n title: 'Get SDK Recipe',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default function handler({\n goal,\n runtime,\n collection,\n includeExample,\n}: InferSchema<typeof schema>) {\n try {\n const recipe = getRecipe(goal, runtime)\n if (!recipe) {\n return toolError(new Error(`No recipe found for goal=\"${goal}\" runtime=\"${runtime}\"`))\n }\n\n let code = recipe.code\n if (collection) {\n code = code.replace(/'products'/g, `'${collection}'`)\n code = code.replace(/'posts'/g, `'${collection}'`)\n }\n\n return toolSuccess({\n recipe: {\n title: recipe.title,\n recommendedSurface: recipe.recommendedSurface,\n runtime: recipe.runtime,\n ...(includeExample ? { code } : {}),\n cautions: recipe.cautions,\n relatedResources: recipe.relatedResources,\n relatedTools: recipe.relatedTools,\n },\n })\n } catch (error) {\n return toolError(error)\n }\n}\n","/**\n * Static recipe map for SDK guidance tools.\n * Keyed by goal → runtime → SdkRecipe.\n */\n\nexport interface SdkRecipe {\n title: string\n recommendedSurface: 'query-builder' | 'react-query' | 'server-api' | 'customer-api'\n runtime: 'browser' | 'server' | 'both'\n code: string\n cautions: string[]\n relatedResources: string[]\n relatedTools: string[]\n}\n\nconst recipes: Record<string, Record<string, SdkRecipe>> = {\n 'fetch-list': {\n browser: {\n title: 'Fetch collection list (browser)',\n recommendedSurface: 'react-query',\n runtime: 'browser',\n code: `import { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n})\n\n// React Query hook — handles caching and background updates\nfunction ProductList() {\n const { data, isLoading, error } = client.query.useQuery({\n collection: 'products',\n options: {\n where: { status: { equals: 'published' } },\n limit: 20,\n sort: '-createdAt',\n },\n })\n\n if (isLoading) return <div>Loading...</div>\n if (error) return <div>Error: {error.message}</div>\n\n return (\n <ul>\n {data?.docs.map((product) => (\n <li key={product.id}>{product.title}</li>\n ))}\n </ul>\n )\n}`,\n cautions: [\n 'createClient is read-only — cannot perform write operations',\n 'Use NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY (not SOFTWARE_PUBLISHABLE_KEY) in browser environments',\n 'useQuery must be used inside a React component wrapped by QueryClientProvider',\n ],\n relatedResources: ['docs://sdk/react-query', 'docs://sdk/query-builder'],\n relatedTools: ['query-collection'],\n },\n server: {\n title: 'Fetch collection list (server)',\n recommendedSurface: 'query-builder',\n runtime: 'server',\n code: `import { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// Query Builder — returns PayloadFindResponse\nconst result = await client.collections.from('products').find({\n where: { status: { equals: 'published' } },\n limit: 20,\n sort: '-createdAt',\n page: 1,\n})\n\n// result.docs — array of documents\n// result.totalDocs — total count\n// result.totalPages — total pages\n// result.hasNextPage — boolean`,\n cautions: [\n 'SOFTWARE_PUBLISHABLE_KEY and SOFTWARE_SECRET_KEY must both be set for server client',\n 'Never expose SOFTWARE_SECRET_KEY to the browser',\n ],\n relatedResources: ['docs://sdk/query-builder', 'docs://sdk/getting-started'],\n relatedTools: ['query-collection'],\n },\n },\n\n 'fetch-by-id': {\n browser: {\n title: 'Fetch single item by ID (browser)',\n recommendedSurface: 'react-query',\n runtime: 'browser',\n code: `import { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n})\n\nfunction ProductDetail({ id }: { id: string }) {\n const { data, isLoading } = client.query.useQueryById({\n collection: 'products',\n id,\n })\n\n if (isLoading) return <div>Loading...</div>\n\n return <div>{data?.title}</div>\n}`,\n cautions: [\n 'Returns undefined while loading — guard with isLoading check',\n 'Throws if the item does not exist',\n ],\n relatedResources: ['docs://sdk/react-query', 'docs://sdk/query-builder'],\n relatedTools: ['get-collection-by-id'],\n },\n server: {\n title: 'Fetch single item by ID (server)',\n recommendedSurface: 'query-builder',\n runtime: 'server',\n code: `import { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// findById returns the document directly (not wrapped in a response object)\nconst product = await client.collections.from('products').findById('product-id')\nconsole.log(product.title)`,\n cautions: [\n 'findById throws if the item does not exist — wrap in try/catch',\n 'Returns the document directly, not a PayloadFindResponse',\n ],\n relatedResources: ['docs://sdk/query-builder'],\n relatedTools: ['get-collection-by-id'],\n },\n },\n\n 'create-item': {\n server: {\n title: 'Create a new item (server only)',\n recommendedSurface: 'server-api',\n runtime: 'server',\n code: `import { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// create() returns PayloadMutationResponse\nconst result = await client.collections.from('products').create({\n title: 'New Product',\n status: 'draft',\n})\n\n// result.doc — the created document\n// result.message — success message`,\n cautions: [\n 'Requires ServerClient — not available on browser client',\n 'All required fields must be provided or the request will fail',\n 'Returns result.doc (not the document directly)',\n ],\n relatedResources: ['docs://sdk/query-builder'],\n relatedTools: ['query-collection', 'get-collection-schema'],\n },\n },\n\n 'update-item': {\n server: {\n title: 'Update an existing item (server only)',\n recommendedSurface: 'server-api',\n runtime: 'server',\n code: `import { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// update() supports partial updates — only include changed fields\nconst result = await client.collections.from('products').update('product-id', {\n title: 'Updated Title',\n status: 'published',\n})\n\n// result.doc — the updated document\n// result.message — success message`,\n cautions: [\n 'Requires ServerClient — not available on browser client',\n 'Throws if the item with the given ID does not exist',\n 'Partial updates are supported — omitted fields retain their current value',\n ],\n relatedResources: ['docs://sdk/query-builder'],\n relatedTools: ['get-collection-by-id', 'get-collection-schema'],\n },\n },\n\n 'delete-item': {\n server: {\n title: 'Delete an item (server only)',\n recommendedSurface: 'server-api',\n runtime: 'server',\n code: `import { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// remove() returns the deleted document directly\nconst deleted = await client.collections.from('products').remove('product-id')\nconsole.log('Deleted:', deleted.title)`,\n cautions: [\n 'Requires ServerClient — not available on browser client',\n 'Deletion is permanent — collections with soft-delete (trash: true) move items to trash instead',\n 'Throws if the item does not exist',\n ],\n relatedResources: ['docs://sdk/query-builder'],\n relatedTools: ['get-collection-by-id', 'query-collection'],\n },\n },\n\n 'infinite-scroll': {\n browser: {\n title: 'Infinite scroll (browser)',\n recommendedSurface: 'react-query',\n runtime: 'browser',\n code: `import { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n})\n\nfunction InfiniteProductList() {\n const {\n data,\n fetchNextPage,\n hasNextPage,\n isFetchingNextPage,\n isLoading,\n } = client.query.useInfiniteQuery({\n collection: 'products',\n options: { where: { status: { equals: 'published' } } },\n pageSize: 20,\n })\n\n const allProducts = data?.pages.flatMap((page) => page.docs) ?? []\n\n return (\n <div>\n {allProducts.map((product) => (\n <div key={product.id}>{product.title}</div>\n ))}\n {hasNextPage && (\n <button onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>\n {isFetchingNextPage ? 'Loading...' : 'Load more'}\n </button>\n )}\n </div>\n )\n}`,\n cautions: [\n 'data.pages is an array of pages — flatten with flatMap to get all docs',\n 'Use useSuspenseInfiniteQuery for Suspense mode',\n 'pageSize controls items per page loaded by fetchNextPage',\n ],\n relatedResources: ['docs://sdk/react-query'],\n relatedTools: ['query-collection'],\n },\n },\n\n 'ssr-prefetch': {\n server: {\n title: 'SSR data prefetching (server)',\n recommendedSurface: 'react-query',\n runtime: 'server',\n code: `import { createServerClient } from '@01.software/sdk'\nimport { dehydrate, HydrationBoundary } from '@tanstack/react-query'\n\n// In a Next.js Server Component or getServerSideProps:\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// Prefetch list — client hydrates instantly without a loading state\nawait client.query.prefetchQuery({\n collection: 'products',\n options: { limit: 20 },\n})\n\n// Prefetch single item\nawait client.query.prefetchQueryById({\n collection: 'products',\n id: 'product-id',\n})\n\n// Prefetch infinite list\nawait client.query.prefetchInfiniteQuery({\n collection: 'products',\n pageSize: 20,\n})\n\n// Dehydrate and pass to client\nconst state = dehydrate(client.query.queryClient)\n\nexport default function Page() {\n return (\n <HydrationBoundary state={state}>\n {/* child components use useSuspenseQuery — no loading state */}\n </HydrationBoundary>\n )\n}`,\n cautions: [\n 'Prefetch must use the same query key as the client hook — options must match exactly',\n 'Use HydrationBoundary to pass dehydrated state to the client',\n 'prefetchQuery does not throw on error — errors surface on the client',\n ],\n relatedResources: ['docs://sdk/react-query'],\n relatedTools: ['query-collection'],\n },\n },\n\n 'customer-auth': {\n browser: {\n title: 'Customer login/register flow (browser)',\n recommendedSurface: 'customer-api',\n runtime: 'browser',\n code: `import { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n})\n\n// --- Register ---\nconst { customer } = await client.customer.register({\n name: 'Jane Doe',\n email: 'jane@example.com',\n password: 'securePassword123',\n phone: '+821012345678', // optional\n})\n\n// --- Login ---\nconst { token, customer: loggedIn } = await client.customer.login({\n email: 'jane@example.com',\n password: 'securePassword123',\n})\n\n// --- Get current customer ---\nconst profile = await client.customer.me()\n\n// --- Update profile (only name, phone, marketingConsent) ---\nawait client.customer.updateProfile({ name: 'Jane Smith' })\n\n// --- Logout ---\nclient.customer.logout()\n\n// --- Password reset flow ---\nawait client.customer.forgotPassword('jane@example.com') // sends token via webhook\nawait client.customer.resetPassword(token, 'newPassword123')`,\n cautions: [\n 'customer.register/login/me are only available on Client (not ServerClient)',\n 'registration creates a local customer account; add app-level verification if your project requires it',\n 'updateProfile only accepts name, phone, and marketingConsent — not email or password',\n 'forgotPassword sends the token to configured tenant webhooks; your webhook handler owns email/SMS delivery',\n ],\n relatedResources: ['docs://sdk/customer-auth', 'docs://sdk/getting-started'],\n relatedTools: [],\n },\n },\n\n 'file-upload': {\n server: {\n title: 'File upload pattern (server)',\n recommendedSurface: 'server-api',\n runtime: 'server',\n code: `import { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// Upload to the 'images' collection (unified tenant image collection)\n// Pass a FormData object with the file attached under the 'file' key\nconst formData = new FormData()\nformData.append('file', fileBlob, 'photo.jpg')\nformData.append('alt', 'Product photo')\n\nconst result = await client.collections.from('images').create(formData as unknown as Record<string, unknown>)\n// result.doc.url — CDN URL of the uploaded image\n// result.doc.id — image ID for use in relationship fields`,\n cautions: [\n 'Images collection (slug: images) is the unified upload collection — use it for all image assets',\n 'brand-logos and tenant-logos are separate upload collections for logos',\n 'system-media is for platform-level assets (not tenant-scoped)',\n 'Always set alt text for accessibility',\n ],\n relatedResources: ['docs://sdk/query-builder'],\n relatedTools: ['query-collection', 'get-collection-schema'],\n },\n },\n\n 'bulk-operations': {\n server: {\n title: 'Bulk update/delete (server only)',\n recommendedSurface: 'server-api',\n runtime: 'server',\n code: `import { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// Bulk update — all documents matching the where clause\nconst updated = await client.collections.from('products').updateMany(\n { status: { equals: 'draft' } }, // where\n { status: 'published' }, // data to apply\n)\n// updated.docs — array of updated documents\n// updated.totalDocs — count of updated documents\n\n// Bulk delete — all documents matching the where clause\nconst removed = await client.collections.from('products').removeMany(\n { status: { equals: 'archived' } },\n)\n// removed.docs — array of deleted documents\n// removed.totalDocs — count of deleted documents`,\n cautions: [\n 'Requires ServerClient — not available on browser client',\n 'removeMany is permanent — double-check the where clause before executing',\n 'No dry-run mode — consider querying with find() first to preview affected docs',\n 'Very broad where clauses (or empty) will affect all documents in the collection',\n ],\n relatedResources: ['docs://sdk/query-builder'],\n relatedTools: ['query-collection', 'get-collection-schema'],\n },\n },\n}\n\n/**\n * Look up a recipe by goal and optional runtime.\n *\n * If runtime is 'both' or not provided, preference order is: server → browser.\n * Returns null when no matching recipe exists.\n */\nexport function getRecipe(goal: string, runtime: string = 'both'): SdkRecipe | null {\n const byGoal = recipes[goal]\n if (!byGoal) return null\n\n if (runtime !== 'both') {\n return byGoal[runtime] ?? null\n }\n\n // Prefer server over browser when runtime is unspecified\n return byGoal['server'] ?? byGoal['browser'] ?? null\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { searchDocs } from '../lib/sdk-doc-index'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n query: z\n .string()\n .min(2)\n .describe('Search keyword or phrase (e.g. \"infinite scroll\", \"webhook\", \"customer login\")'),\n limit: z\n .number()\n .min(1)\n .max(10)\n .default(5)\n .describe('Maximum results to return (1-10, default: 5)'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'sdk-search-docs',\n description:\n 'Search SDK documentation by keyword. Returns matching topics with summaries and resource links. Use when looking for specific SDK features or patterns.',\n annotations: {\n title: 'Search SDK Docs',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nexport default function handler({\n query,\n limit,\n}: InferSchema<typeof schema>) {\n try {\n const results = searchDocs(query, limit)\n\n if (results.length === 0) {\n return toolSuccess({\n results: [],\n message: `No documentation found for \"${query}\". Try broader terms.`,\n })\n }\n\n return toolSuccess({\n results: results.map((r) => ({\n title: r.title,\n summary: r.summary,\n resourceUri: r.resourceUri,\n })),\n })\n } catch (error) {\n return toolError(error)\n }\n}\n","/**\n * Static search index for SDK documentation topics.\n * Supports case-insensitive keyword matching with rank by match count.\n */\n\nexport interface DocEntry {\n title: string\n keywords: string[]\n summary: string\n resourceUri: string\n}\n\nconst docIndex: DocEntry[] = [\n // Getting started\n {\n title: 'Getting Started',\n keywords: ['install', 'setup', 'quickstart', 'getting started', 'create client', 'init', 'introduction'],\n summary: 'Install the SDK, create a client instance, and make your first query.',\n resourceUri: 'docs://sdk/getting-started',\n },\n {\n title: 'Browser Client vs Server Client',\n keywords: ['browser', 'server', 'publishable key', 'secret key', 'createClient', 'createServerClient', 'NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY', 'SOFTWARE_PUBLISHABLE_KEY', 'SOFTWARE_SECRET_KEY', 'pk01_', 'sk01_', 'pat01_', 'read-only', 'full crud'],\n summary: 'createClient() for browser with publishableKey (read-only pk01_), createServerClient() for server with matching SOFTWARE_PUBLISHABLE_KEY + SOFTWARE_SECRET_KEY (usually sk01_, sometimes pat01_ in scoped flows). Never expose SECRET_KEY to the browser.',\n resourceUri: 'docs://sdk/getting-started',\n },\n\n // Query Builder\n {\n title: 'Query Builder — find()',\n keywords: ['find', 'list', 'query', 'fetch', 'query builder', 'from', 'paginate', 'pagination', 'where', 'limit', 'page', 'sort'],\n summary: 'client.collections.from(collection).find({ where, limit, page, sort }) returns PayloadFindResponse with docs array and pagination metadata.',\n resourceUri: 'docs://sdk/query-builder',\n },\n {\n title: 'Query Builder — findById()',\n keywords: ['findById', 'get by id', 'single item', 'document by id', 'query builder'],\n summary: 'client.collections.from(collection).findById(id) returns the document directly. Throws if not found.',\n resourceUri: 'docs://sdk/query-builder',\n },\n {\n title: 'Query Builder — count()',\n keywords: ['count', 'total', 'totalDocs', 'query builder'],\n summary: 'client.collections.from(collection).count() returns { totalDocs }. Accepts an optional where filter.',\n resourceUri: 'docs://sdk/query-builder',\n },\n {\n title: 'Query Builder — create(), update(), remove()',\n keywords: ['create', 'update', 'delete', 'remove', 'mutation', 'write', 'server client', 'query builder', 'crud'],\n summary: 'Write operations require ServerClient. create() and update() return PayloadMutationResponse ({ doc, message }). remove() returns the deleted document directly.',\n resourceUri: 'docs://sdk/query-builder',\n },\n {\n title: 'Query Builder — updateMany() and removeMany()',\n keywords: ['updateMany', 'removeMany', 'bulk', 'bulk update', 'bulk delete', 'batch', 'query builder', 'server client'],\n summary: 'Bulk operations on all documents matching a where clause. Requires ServerClient. Returns PayloadFindResponse with affected docs.',\n resourceUri: 'docs://sdk/query-builder',\n },\n {\n title: 'Query Builder — Metadata Generation',\n keywords: ['metadata', 'findMetadata', 'findMetadataById', 'next.js metadata', 'seo', 'open graph', 'query builder'],\n summary: 'client.collections.from(collection).findMetadata(options, config) and findMetadataById(id, config) generate Next.js Metadata objects from collection fields.',\n resourceUri: 'docs://sdk/query-builder',\n },\n\n // React Query Hooks\n {\n title: 'React Query — useQuery()',\n keywords: ['useQuery', 'react query', 'hook', 'list', 'fetch', 'collection', 'cache', 'react'],\n summary: 'client.query.useQuery({ collection, options }) — fetches a list with caching and background updates. Use inside a React component.',\n resourceUri: 'docs://sdk/react-query',\n },\n {\n title: 'React Query — useSuspenseQuery() and useSuspenseQueryById()',\n keywords: ['useSuspenseQuery', 'useSuspenseQueryById', 'suspense', 'react query', 'hook', 'streaming'],\n summary: 'Suspense-mode hooks for list and single-item queries. Use with React Suspense boundaries.',\n resourceUri: 'docs://sdk/react-query',\n },\n {\n title: 'React Query — useInfiniteQuery()',\n keywords: ['useInfiniteQuery', 'useSuspenseInfiniteQuery', 'infinite scroll', 'load more', 'pagination', 'react query', 'hook'],\n summary: 'client.query.useInfiniteQuery({ collection, options, pageSize }) — infinite scrolling. data.pages is an array of pages; flatten with flatMap for all docs.',\n resourceUri: 'docs://sdk/react-query',\n },\n {\n title: 'React Query — useCreate(), useUpdate(), useRemove()',\n keywords: ['useCreate', 'useUpdate', 'useRemove', 'mutation hook', 'react query', 'cache invalidation', 'mutate'],\n summary: 'Mutation hooks with automatic cache invalidation. Require the component tree to have access to the same QueryClient instance.',\n resourceUri: 'docs://sdk/react-query',\n },\n\n // Caching\n {\n title: 'SSR Prefetching and Cache Hydration',\n keywords: ['prefetch', 'ssr', 'server side rendering', 'prefetchQuery', 'prefetchQueryById', 'prefetchInfiniteQuery', 'dehydrate', 'HydrationBoundary', 'cache'],\n summary: 'Prefetch data in Server Components, dehydrate with @tanstack/react-query, and pass via HydrationBoundary for instant client hydration.',\n resourceUri: 'docs://sdk/react-query',\n },\n {\n title: 'Cache Invalidation and Manual Cache Management',\n keywords: ['invalidateQueries', 'getQueryData', 'setQueryData', 'cache', 'invalidate', 'optimistic update', 'react query'],\n summary: 'client.query.invalidateQueries(collection, type) triggers refetch. getQueryData/setQueryData allow manual optimistic updates.',\n resourceUri: 'docs://sdk/react-query',\n },\n\n // Filtering\n {\n title: 'Filtering — Payload Query Syntax',\n keywords: ['filter', 'where', 'query syntax', 'equals', 'not_equals', 'greater_than', 'less_than', 'contains', 'like', 'in', 'exists', 'and', 'or', 'payload'],\n summary: 'Use Payload query syntax in the where option. Supports equals, not_equals, greater_than, less_than, contains, like, in, exists, and logical and/or operators.',\n resourceUri: 'docs://sdk/query-builder',\n },\n\n // Customer Auth\n {\n title: 'Customer Auth — Login and Register',\n keywords: ['customer', 'login', 'register', 'auth', 'authentication', 'customer auth'],\n summary: 'client.customer.login({ email, password }) and register({ name, email, password }).',\n resourceUri: 'docs://sdk/customer-auth',\n },\n {\n title: 'Customer Auth — Profile and Password',\n keywords: ['customer', 'profile', 'updateProfile', 'me', 'password', 'forgotPassword', 'resetPassword', 'changePassword', 'logout'],\n summary: 'client.customer.me(), updateProfile({ name, phone, marketingConsent }), forgotPassword(email), resetPassword(token, newPassword). Only available on Client (not ServerClient).',\n resourceUri: 'docs://sdk/customer-auth',\n },\n {\n title: 'Customer Auth — Token Management',\n keywords: ['customer', 'token', 'jwt', 'getToken', 'setToken', 'isAuthenticated', 'refreshToken', 'logout'],\n summary: 'client.customer.getToken(), setToken(token), isAuthenticated(), refreshToken(), logout() for managing the customer JWT manually.',\n resourceUri: 'docs://sdk/customer-auth',\n },\n\n // File upload\n {\n title: 'File Upload',\n keywords: ['upload', 'file', 'image', 'images', 'media', 'FormData', 'cdn', 'storage'],\n summary: 'Upload to the images collection (unified tenant image store) via create() with a FormData payload. Returns result.doc.url for the CDN URL.',\n resourceUri: 'docs://sdk/query-builder',\n },\n\n // Webhooks\n {\n title: 'Webhooks',\n keywords: ['webhook', 'hmac', 'signature', 'WEBHOOK_SECRET', 'server-to-server', 'event'],\n summary: 'Tenant webhooks deliver server-to-server events such as password reset tokens. Signed with HMAC-SHA256 using PAYLOAD_SECRET.',\n resourceUri: 'docs://sdk/webhook',\n },\n\n // Order API\n {\n title: 'Order API — createOrder() and checkout()',\n keywords: ['order', 'create order', 'checkout', 'cart checkout', 'orderNumber', 'totalAmount', 'pgPaymentId', 'free order'],\n summary: 'client.commerce.orders.create({ orderNumber, customerSnapshot, orderItems, totalAmount, ... }) or client.commerce.orders.checkout({ cartId, orderNumber, ... }). Omit pgPaymentId for free orders.',\n resourceUri: 'docs://sdk/server-api',\n },\n {\n title: 'Order API — Fulfillment and Shipping',\n keywords: ['fulfillment', 'shipping', 'tracking', 'carrier', 'trackingNumber', 'createFulfillment', 'updateFulfillment', 'shipped', 'delivered'],\n summary: 'client.commerce.orders.createFulfillment({ orderNumber, items, carrier?, trackingNumber? }) creates a shipment. updateFulfillment() advances fulfillment status.',\n resourceUri: 'docs://sdk/server-api',\n },\n {\n title: 'Order API — Returns and Refunds',\n keywords: ['return', 'refund', 'createReturn', 'returnWithRefund', 'return_requested', 'return_processing', 'returned', 'stock restore'],\n summary: 'client.commerce.orders.createReturn() for return-only. client.commerce.orders.returnWithRefund() atomically handles return + stock restoration + transaction cancellation.',\n resourceUri: 'docs://sdk/server-api',\n },\n\n // Cart API\n {\n title: 'Cart API',\n keywords: ['cart', 'add to cart', 'remove from cart', 'cart item', 'applyDiscount', 'removeDiscount', 'clear', 'checkout', 'shippingAmount'],\n summary: 'client.commerce.cart.addItem(), removeItem(), updateItem(), applyDiscount(), removeDiscount(), clear(). Cart is tenant-scoped and customer-linked.',\n resourceUri: 'docs://sdk/server-api',\n },\n]\n\n/**\n * Search the doc index by query string.\n *\n * Performs case-insensitive keyword matching against title and keywords.\n * Results are ranked by number of matching terms (descending).\n */\nexport function searchDocs(query: string, limit: number = 5): DocEntry[] {\n if (!query.trim()) return docIndex.slice(0, limit)\n\n const terms = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 1)\n\n if (terms.length === 0) return docIndex.slice(0, limit)\n\n const scored = docIndex.map((entry) => {\n const haystack = [entry.title, ...entry.keywords].join(' ').toLowerCase()\n let score = 0\n for (const term of terms) {\n if (haystack.includes(term)) score++\n }\n return { entry, score }\n })\n\n return scored\n .filter(({ score }) => score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, limit)\n .map(({ entry }) => entry)\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n scenario: z\n .enum([\n 'browser-client',\n 'server-client',\n 'customer-auth',\n 'mcp-connection',\n 'server-credentials',\n 'webhook-verification',\n ])\n .describe('Authentication scenario'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'sdk-get-auth-setup',\n description:\n 'Get the current authentication setup for a specific scenario. Returns env var names, code snippets, and security notes.',\n annotations: {\n title: 'Get Auth Setup',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nconst AUTH_GUIDES: Record<string, { title: string; envVars: string[]; code: string; notes: string[] }> = {\n 'browser-client': {\n title: 'Browser Client Setup',\n envVars: ['NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY'],\n code: `import { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!\n})\n\n// Read-only operations + React Query hooks + Customer Auth\nconst { data } = client.query.useQuery({ collection: 'products' })`,\n notes: [\n 'Client is read-only — no create/update/delete operations',\n 'publishableKey is safe to expose in browser (prefixed with NEXT_PUBLIC_)',\n 'Includes React Query hooks (client.query) and Customer Auth (client.customer)',\n ],\n },\n 'server-client': {\n title: 'Server Client Setup',\n envVars: ['SOFTWARE_PUBLISHABLE_KEY', 'SOFTWARE_SECRET_KEY'],\n code: `import { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!\n})\n\n// Full CRUD operations\nconst result = await client.collections.from('products').create({ title: 'New Product' })`,\n notes: [\n 'ServerClient has full CRUD access and must run only in trusted server code',\n 'Store server credentials in environment variables and rotate them from the Console',\n 'Use in API routes, server actions, or backend services only',\n 'React Query hooks available for reads (useQuery, prefetchQuery, etc.) + mutations (useCreate, useUpdate, useRemove)',\n ],\n },\n 'customer-auth': {\n title: 'Customer Authentication',\n envVars: ['NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY'],\n code: `import { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!\n})\n\n// Register\nconst { customer } = await client.customer.register({\n email: 'user@example.com',\n password: 'password123',\n name: 'John'\n})\n\n// Login\nconst { token, customer } = await client.customer.login({\n email: 'user@example.com',\n password: 'password123'\n})\n\n// Check auth status\nclient.customer.isAuthenticated()`,\n notes: [\n 'Customer auth uses the browser Client (not ServerClient)',\n 'JWT tokens are managed automatically by the SDK',\n 'Registration creates a local customer account; add application-level verification if needed',\n ],\n },\n 'mcp-connection': {\n title: 'MCP Server Connection',\n envVars: [],\n code: `# Claude Code\nclaude mcp add --transport http 01software https://mcp.01.software/mcp\n\n# Codex .codex/config.toml\n[mcp_servers.01software]\nurl = \"https://mcp.01.software/mcp\"\n\n# Or use JSON clients that support OAuth discovery\n{\n \"mcpServers\": {\n \"01software\": {\n \"type\": \"http\",\n \"url\": \"https://mcp.01.software/mcp\"\n }\n }\n}`,\n notes: [\n 'HTTP MCP uses OAuth discovery and Authorization Code + PKCE',\n 'Clients that cannot complete OAuth discovery are unsupported until a smoke test proves compatibility',\n 'stdio transport remains a local CLI path and is separate from HTTP MCP OAuth discovery',\n ],\n },\n 'server-credentials': {\n title: 'Server Credential Management',\n envVars: ['SOFTWARE_PUBLISHABLE_KEY', 'SOFTWARE_SECRET_KEY'],\n code: `# Server credentials are managed from the Console, not in code.\n# Copy both values from the same tenant.\n\n# Use them together for CLI and server SDK calls.\nexport SOFTWARE_PUBLISHABLE_KEY=pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nexport SOFTWARE_SECRET_KEY=sk01_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`,\n notes: [\n 'The matching SOFTWARE_PUBLISHABLE_KEY is still required for tenant routing, rate limits, and quota enforcement',\n 'Used for REST/SDK authentication in trusted server contexts',\n 'Manage credentials from the Console and rotate them on exposure',\n ],\n },\n 'webhook-verification': {\n title: 'Webhook Verification',\n envVars: ['WEBHOOK_SECRET'],\n code: `import { handleWebhook, createCustomerAuthWebhookHandler } from '@01.software/sdk/webhook'\n\nconst customerAuthHandler = createCustomerAuthWebhookHandler({\n passwordReset: sendPasswordResetEmail,\n})\n\nexport async function POST(request: Request) {\n return handleWebhook(request, customerAuthHandler, {\n secret: process.env.WEBHOOK_SECRET!,\n })\n}`,\n notes: [\n 'handleWebhook() takes (request, handler, options) — handler receives the parsed event',\n 'WEBHOOK_SECRET is set per-tenant in Console > Settings',\n 'handleWebhook() verifies HMAC-SHA256 signature automatically before calling handler',\n 'createCustomerAuthWebhookHandler() is optional; it just routes auth events to your own email/SMS delivery code',\n ],\n },\n}\n\nexport default function handler({\n scenario,\n}: InferSchema<typeof schema>) {\n try {\n const guide = AUTH_GUIDES[scenario]\n if (!guide) {\n return toolError(new Error(`Unknown auth scenario: ${scenario}`))\n }\n return toolSuccess({ guide })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type ToolMetadata, type InferSchema } from '../types'\nimport { COLLECTIONS, SERVER_COLLECTIONS } from '@01.software/sdk'\nimport { toolSuccess, toolError } from '../lib/tool-utils'\n\nexport const schema = {\n collection: z.enum(SERVER_COLLECTIONS).describe('Collection name'),\n operation: z\n .enum(['read', 'write', 'full-crud'])\n .default('read')\n .describe('What operations are needed'),\n surface: z\n .enum(['query-builder', 'react-query', 'server-api'])\n .default('query-builder')\n .describe('Preferred API surface'),\n} as const\n\nexport const metadata: ToolMetadata = {\n name: 'sdk-get-collection-pattern',\n description:\n 'Get the recommended CRUD pattern for a specific collection. Returns code examples for the chosen API surface and operation type.',\n annotations: {\n title: 'Get Collection Pattern',\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n },\n}\n\nfunction generatePattern(\n collection: string,\n operation: string,\n surface: string,\n): { code: string; notes: string[] } {\n const isPublicCollection = COLLECTIONS.includes(\n collection as (typeof COLLECTIONS)[number],\n )\n\n if (surface === 'react-query') {\n if (!isPublicCollection) {\n throw new Error(\n `${collection} is server-only. Use surface=\"server-api\" with createServerClient().`,\n )\n }\n const parts: string[] = []\n\n if (operation === 'read') {\n parts.push(\n `import { createClient } from '@01.software/sdk'`,\n ``,\n `const client = createClient({`,\n ` publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!`,\n `})`,\n ``,\n )\n } else {\n // write or full-crud: mutation hooks require ServerClient\n parts.push(\n `import { createServerClient } from '@01.software/sdk'`,\n ``,\n `// Mutation hooks require ServerClient`,\n `const client = createServerClient({`,\n ` publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,`,\n ` secretKey: process.env.SOFTWARE_SECRET_KEY!`,\n `})`,\n ``,\n )\n }\n\n if (operation === 'read' || operation === 'full-crud') {\n parts.push(\n `// List query`,\n `const { data, isLoading } = client.query.useQuery({`,\n ` collection: '${collection}',`,\n ` options: { limit: 10 }`,\n `})`,\n ``,\n `// Single item`,\n `const { data: item } = client.query.useQueryById({`,\n ` collection: '${collection}',`,\n ` id: itemId`,\n `})`,\n )\n }\n\n if (operation === 'write' || operation === 'full-crud') {\n parts.push(\n ``,\n `// Create (auto cache invalidation)`,\n `const { mutate: create } = client.query.useCreate({ collection: '${collection}' })`,\n `create({ title: 'New Item' })`,\n ``,\n `// Update`,\n `const { mutate: update } = client.query.useUpdate({ collection: '${collection}' })`,\n `update({ id: itemId, data: { title: 'Updated' } })`,\n ``,\n `// Delete`,\n `const { mutate: remove } = client.query.useRemove({ collection: '${collection}' })`,\n `remove(itemId)`,\n )\n }\n\n return {\n code: parts.join('\\n'),\n notes: [\n 'React Query hooks provide automatic caching and background updates',\n 'Mutation hooks auto-invalidate related query caches',\n operation === 'write' || operation === 'full-crud'\n ? 'Mutation hooks (useCreate, useUpdate, useRemove) require ServerClient with SOFTWARE_PUBLISHABLE_KEY + SOFTWARE_SECRET_KEY'\n : 'Read hooks work in browser components',\n ],\n }\n }\n\n if (surface === 'server-api') {\n const parts: string[] = [\n `import { createServerClient } from '@01.software/sdk'`,\n ``,\n `const client = createServerClient({`,\n ` publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,`,\n ` secretKey: process.env.SOFTWARE_SECRET_KEY!`,\n `})`,\n ``,\n ]\n\n if (operation === 'read' || operation === 'full-crud') {\n parts.push(\n `// Query list`,\n `const result = await client.collections.from('${collection}').find({`,\n ` where: { status: { equals: 'published' } },`,\n ` limit: 10,`,\n ` sort: '-createdAt'`,\n `})`,\n `// result.docs, result.totalDocs, result.hasNextPage`,\n ``,\n `// Single item`,\n `const item = await client.collections.from('${collection}').findById(id)`,\n )\n }\n\n if (operation === 'write' || operation === 'full-crud') {\n parts.push(\n ``,\n `// Create`,\n `const created = await client.collections.from('${collection}').create({ title: 'New' })`,\n `// created.doc, created.message`,\n ``,\n `// Update`,\n `const updated = await client.collections.from('${collection}').update(id, { title: 'Updated' })`,\n ``,\n `// Delete`,\n `await client.collections.from('${collection}').remove(id)`,\n )\n }\n\n return {\n code: parts.join('\\n'),\n notes: [\n 'ServerClient required for write operations',\n 'Never expose secretKey in browser code',\n 'Use in API routes, server actions, or backend services',\n ],\n }\n }\n\n // Default: query-builder\n const parts: string[] = []\n\n if (operation === 'read' || operation === 'full-crud') {\n if (isPublicCollection) {\n parts.push(\n `// Read with any client (Client or ServerClient)`,\n `const result = await client.collections.from('${collection}').find({`,\n ` where: { status: { equals: 'published' } },`,\n ` limit: 10,`,\n ` sort: '-createdAt'`,\n `})`,\n ``,\n `const item = await client.collections.from('${collection}').findById(id)`,\n `const { totalDocs } = await client.collections.from('${collection}').count()`,\n )\n } else {\n parts.push(\n `// Server-only collection: use ServerClient`,\n `const result = await serverClient.collections.from('${collection}').find({`,\n ` limit: 10,`,\n ` sort: '-createdAt'`,\n `})`,\n ``,\n `const item = await serverClient.collections.from('${collection}').findById(id)`,\n )\n }\n }\n\n if (operation === 'write' || operation === 'full-crud') {\n parts.push(\n ``,\n `// Write operations (ServerClient only)`,\n `const created = await serverClient.collections.from('${collection}').create({ title: 'New' })`,\n `const updated = await serverClient.collections.from('${collection}').update(id, { title: 'Updated' })`,\n `await serverClient.collections.from('${collection}').remove(id)`,\n )\n }\n\n return {\n code: parts.join('\\n'),\n notes: [\n 'Query Builder works with both Client and ServerClient for reads',\n !isPublicCollection ? 'This collection is server-only' : '',\n operation !== 'read' ? 'Write operations require ServerClient' : '',\n ].filter(Boolean),\n }\n}\n\nexport default function handler({\n collection,\n operation,\n surface,\n}: InferSchema<typeof schema>) {\n try {\n const pattern = generatePattern(collection, operation, surface)\n\n return toolSuccess({\n collection,\n operation,\n surface,\n ...pattern,\n relatedTools: [\n 'query-collection',\n 'get-collection-by-id',\n 'get-collection-schema',\n ],\n relatedResources: [\n surface === 'react-query'\n ? 'docs://sdk/react-query'\n : 'docs://sdk/query-builder',\n 'docs://sdk/browser-vs-server',\n ],\n })\n } catch (error) {\n return toolError(error)\n }\n}\n","import { z } from 'zod'\nimport { type PromptMetadata, type InferSchema } from '../types'\n\nexport const schema = {\n goal: z\n .string()\n .describe('What the user wants to accomplish (e.g., \"query product list\", \"create order\")'),\n runtime: z\n .enum(['browser', 'server'])\n .optional()\n .describe('Target runtime: browser (React/Next.js client) or server (Node.js)'),\n surface: z\n .enum(['query-builder', 'react-query', 'customer-api', 'server-api'])\n .optional()\n .describe('Preferred API surface'),\n collection: z\n .string()\n .optional()\n .describe('Specific collection if relevant'),\n} as const\n\nexport const metadata: PromptMetadata = {\n name: 'sdk-usage-guide',\n title: 'SDK Usage Guide',\n description:\n 'Provides guidance on how to perform a specific task using the 01.software SDK',\n role: 'assistant',\n}\n\nexport default function sdkUsageGuide({ goal, runtime, surface, collection }: InferSchema<typeof schema>) {\n const context = [\n `Goal: \"${goal}\"`,\n runtime ? `Runtime: ${runtime}` : null,\n surface ? `Surface: ${surface}` : null,\n collection ? `Collection: ${collection}` : null,\n ].filter(Boolean).join(' | ')\n\n return `Guide on how to perform \"${goal}\" using the 01.software SDK.\n${context}\n\n## 01.software SDK Overview\n\n01.software SDK is a powerful TypeScript client library for React and Next.js applications.\n\n### Key Features\n- Modern TypeScript - Full type safety\n- React Query Integration - Built-in caching, background updates\n- Universal - Works in both browser and server environments\n- Intuitive API - Clean and expressive query builder interface\n\n### Basic Usage\n\n\\`\\`\\`typescript\nimport { createClient } from '@01.software/sdk'\n\n// Create a client instance\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!\n})\n\n// Fetch data with Query Builder\nconst result = await client.collections.from('products').find({\n where: { status: { equals: 'published' } },\n limit: 10\n})\n\n// Use React hooks\nfunction ProductList() {\n const { data, isLoading } = client.query.useQuery({\n collection: 'products',\n options: { limit: 10 }\n })\n\n if (isLoading) return <div>Loading...</div>\n\n return (\n <div>\n {data?.docs.map(product => (\n <div key={product.id}>{product.title}</div>\n ))}\n </div>\n )\n}\n\\`\\`\\`\n\n### React Query Hooks (client.query)\n\n| Hook | Description |\n|------|-------------|\n| \\`useQuery({ collection, options })\\` | Query collection list |\n| \\`useSuspenseQuery({ collection, options })\\` | Suspense mode list query |\n| \\`useQueryById({ collection, id, options })\\` | Get single item by ID |\n| \\`useSuspenseQueryById({ collection, id, options })\\` | Suspense mode single item |\n| \\`useInfiniteQuery({ collection, options, pageSize })\\` | Infinite scroll |\n| \\`useSuspenseInfiniteQuery({ collection, options, pageSize })\\` | Suspense infinite scroll |\n\n### Query Builder (client.collections.from)\n\n\\`\\`\\`typescript\n// Read operations - find() returns PayloadFindResponse with docs array\nconst result = await client.collections.from('products').find({ limit: 20 })\n// result.docs, result.totalDocs, result.page, result.totalPages, ...\n\n// findById() returns the document directly\nconst product = await client.collections.from('products').findById('id')\n\n// Write operations (ServerClient only)\n// create()/update() returns PayloadMutationResponse with doc and message\nconst created = await client.collections.from('products').create({ title: 'New', status: 'draft' })\n// created.doc, created.message\n\nconst updated = await client.collections.from('products').update('id', { title: 'Updated' })\n// updated.doc, updated.message\n\n// remove() returns the deleted document directly\nawait client.collections.from('products').remove('id')\n\n// count() returns { totalDocs }\nconst { totalDocs } = await client.collections.from('products').count()\n\n// Metadata - generate Next.js Metadata from collection fields\n// Auto-maps per-collection fields (e.g. articles: description→description, thumbnail→image)\nconst articleMeta = await client.collections.from('articles').findMetadataById(id, { siteName: 'My Blog' })\nconst productMeta = await client.collections.from('products').findMetadata(\n { where: { slug: { equals: 'my-product' } } },\n { siteName: 'My Store' }\n)\n\\`\\`\\`\n\n### Filtering (Payload Query Syntax)\n\n\\`\\`\\`typescript\nconst items = await client.collections.from('products').find({\n where: {\n status: { equals: 'published' },\n 'listing.minPrice': { greater_than: 1000 },\n or: [\n { category: { equals: 'electronics' } },\n { featured: { equals: true } }\n ]\n }\n})\n\\`\\`\\`\n\nFor ecommerce collections, use \\`products.listing.*\\` for browse/search pricing and \\`product-variants.price\\` for authoritative sellable price.\n\n### Server Client (Server-side)\n\n\\`\\`\\`typescript\nimport { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!\n})\n\\`\\`\\`\n\nYou can perform the \"${goal}\" task by following the patterns above.\n\n## Common recipes\n\n### Product detail page (slug-based)\n\n\\`\\`\\`typescript\nconst product = await client.commerce.product.detail({ slug })\nif (!product) return notFound()\n// product: { product, variants, options, brand, categories, tags, images, videos, listing }\n\\`\\`\\`\n\nFor React: \\`const { data } = client.query.useProductDetailBySlug(slug)\\`.\n\n### Product listing (grouped)\n\n\\`\\`\\`typescript\nconst { docs } = await client.commerce.product.listingGroups({ productIds })\n\\`\\`\\`\n\n### Stock check before adding to cart\n\n\\`\\`\\`typescript\nconst { allAvailable } = await client.commerce.product.stockCheck({\n items: [{ variantId, quantity }],\n})\n\\`\\`\\``\n}\n","import { z } from 'zod'\nimport { type PromptMetadata, type InferSchema } from '../types'\nimport { COLLECTIONS, SERVER_COLLECTIONS } from '@01.software/sdk'\n\nexport const schema = {\n collection: z.enum(SERVER_COLLECTIONS).describe('Collection name'),\n operation: z\n .enum(['find', 'create', 'update', 'delete'])\n .describe('Operation to perform (find, create, update, delete)'),\n filters: z\n .string()\n .optional()\n .describe('Filter conditions (JSON string, optional)'),\n} as const\n\nexport const metadata: PromptMetadata = {\n name: 'collection-query-help',\n title: 'Collection Query Help',\n description:\n 'Provides guidance on how to write queries for a specific collection',\n role: 'assistant',\n}\n\nexport default function collectionQueryHelp({\n collection,\n operation,\n filters,\n}: InferSchema<typeof schema>) {\n const filterExample = filters\n ? `\\n\\nFilter conditions:\\n\\`\\`\\`json\\n${filters}\\n\\`\\`\\``\n : ''\n const isPublicCollection = COLLECTIONS.includes(\n collection as (typeof COLLECTIONS)[number],\n )\n const readClientName = isPublicCollection ? 'client' : 'serverClient'\n const readClientNote = isPublicCollection\n ? 'Client or ServerClient'\n : 'ServerClient only'\n\n return `How to perform \"${operation}\" operation on \"${collection}\" collection:${filterExample}\n\n## Collection: ${collection}\n## Operation: ${operation}${filterExample}\n\n### ${operation === 'find' ? 'Query' : operation === 'create' ? 'Create' : operation === 'update' ? 'Update' : 'Delete'} Example\n\n\\`\\`\\`typescript\nimport { createClient, createServerClient } from '@01.software/sdk'\n\n// Client (read-only public collections)\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!\n})\n\n// Server client (server/public collections, full CRUD)\nconst serverClient = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!\n})\n\n${\n operation === 'find'\n ? `// Query ${collection} collection with Query Builder (${readClientNote})\n// find() returns PayloadFindResponse with docs array and pagination\nconst result = await ${readClientName}.collections.from('${collection}').find(${\n filters\n ? `{\n where: ${filters}\n}`\n : ''\n })\n// result.docs - array of items\n// result.totalDocs, result.page, result.totalPages, result.hasNextPage, ...\n\n${\n isPublicCollection\n ? `// Using React Hook\nconst { data, isLoading, error } = client.query.useQuery({\n collection: '${collection}',\n options: { limit: 10 }\n})\n\n// With Suspense\nconst { data } = client.query.useSuspenseQuery({\n collection: '${collection}',\n options: { limit: 10 }\n})`\n : `// React hooks are browser/public only and do not support '${collection}'.`\n}`\n : operation === 'create'\n ? `// Create ${collection} item (ServerClient only)\n// create() returns PayloadMutationResponse with doc and message\nconst result = await serverClient.collections.from('${collection}').create({\n // Enter fields\n})\n// result.doc - created item, result.message`\n : operation === 'update'\n ? `// Update ${collection} item (ServerClient only)\n// update() returns PayloadMutationResponse with doc and message\nconst result = await serverClient.collections.from('${collection}').update(id, {\n // Fields to update\n})\n// result.doc - updated item, result.message`\n : `// Delete ${collection} item (ServerClient only)\n// remove() returns the deleted document directly\nawait serverClient.collections.from('${collection}').remove(id)`\n}\n\\`\\`\\`\n\n### Useful Tips\n\n${\n operation === 'find'\n ? `- Use \\`where\\` option for filtering (Payload query syntax)\n- Use \\`limit\\` and \\`page\\` for pagination\n- Use \\`sort\\` for sorting (prefix with \"-\" for descending)\n- ${\n isPublicCollection\n ? 'React Query hooks: useQuery, useSuspenseQuery, useInfiniteQuery'\n : 'React Query hooks are browser/public only; use ServerClient for this collection'\n }\n- Cache utilities: invalidateQueries, prefetchQuery, getQueryData, setQueryData`\n : operation === 'create'\n ? `- Requires ServerClient with secretKey\n- Check required fields\n- TypeScript recommended for type safety`\n : operation === 'update'\n ? `- Requires ServerClient with secretKey\n- Partial updates supported (no need for full object)\n- Non-existent IDs will throw an error`\n : `- Requires ServerClient with secretKey\n- Deletion is permanent, use with caution\n- Recommended to check existence before deletion`\n}`\n}\n","import { z } from 'zod'\nimport { type PromptMetadata, type InferSchema } from '../types'\n\nexport const schema = {\n scenario: z\n .enum([\n 'simple-order',\n 'cart-checkout',\n 'return-refund',\n 'fulfillment-tracking',\n ])\n .describe('Order flow scenario'),\n} as const\n\nexport const metadata: PromptMetadata = {\n name: 'order-flow-guide',\n title: 'Order Flow Guide',\n description:\n 'Provides step-by-step guidance for ecommerce order flows including creation, checkout, returns, and fulfillment.',\n role: 'assistant',\n}\n\nconst SCENARIOS: Record<string, string> = {\n 'simple-order': `## Simple Order Creation\n\n### Flow: Direct Order (no cart)\n\n1. **Create Order** → \\`create-order\\` tool\n - Provide: orderNumber, customerSnapshot (email required), shippingAddress, orderItems, totalAmount\n - Optional: pgPaymentId (omit for free orders), shippingAmount, discountCode\n\n2. **Payment Confirmation** → \\`update-transaction\\` tool\n - Confirm provider payment with pgPaymentId, paymentKey, and amount\n - Stock is automatically adjusted (stock -= qty, reservedStock += qty)\n\n3. **Fulfillment** → \\`create-fulfillment\\` tool\n - Provide carrier + trackingNumber for shipped status\n - Partial shipment → order becomes \\`preparing\\`\n - All items shipped → order becomes \\`shipped\\`\n\n### Code Example (ServerClient)\n\\`\\`\\`typescript\nimport { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!\n})\n\n// 1. Create order\nconst order = await client.commerce.orders.create({\n orderNumber: 'ORD-240101-001',\n customerSnapshot: { email: 'user@example.com', name: 'John' },\n shippingAddress: { postalCode: '06000', address1: '123 Main St' },\n orderItems: [{ product: 'prod-id', variant: 'var-id', option: 'opt-id', quantity: 2 }],\n totalAmount: 59800,\n pgPaymentId: 'pay_xxx' // omit for free orders\n})\n\n// 2. After payment confirmed by provider\nawait client.commerce.orders.updateTransaction({\n pgPaymentId: 'pay_xxx',\n status: 'paid',\n paymentKey: 'payment_key_xxx',\n amount: 59800\n})\n\n// 3. Ship items\nawait client.commerce.orders.createFulfillment({\n orderNumber: 'ORD-240101-001',\n carrier: 'cj',\n trackingNumber: '1234567890',\n items: [{ orderItem: 'oi-id', quantity: 2 }]\n})\n\\`\\`\\``,\n\n 'cart-checkout': `## Cart → Checkout Flow\n\n### Flow\n\n1. **Add Items** → \\`add-cart-item\\` tool\n2. **Apply Discount** (optional) → \\`apply-discount\\` tool\n3. **Calculate Shipping** → \\`calculate-shipping\\` tool\n4. **Checkout** → \\`checkout\\` tool (converts cart to order)\n5. **Payment** → \\`update-transaction\\` for provider-verified paid transitions\n\n### Key Points\n- Cart has a customer linked — auto-copied to order on checkout\n- Cart shippingAddress and shippingAmount are copied to order\n- CartItems → OrderItems conversion is automatic\n- Cart status becomes \\`completed\\` after checkout\n- Free orders (totalAmount=0, no pgPaymentId) auto-transition to \\`paid\\`\n\n### Code Example\n\\`\\`\\`typescript\n// 1. Add items to cart\nawait client.commerce.cart.addItem({ cartId, product: 'prod-id', variant: 'var-id', option: 'opt-id', quantity: 1 })\n\n// 2. Apply discount\nawait client.commerce.cart.applyDiscount({ cartId, discountCode: 'SAVE10' })\n\n// 3. Checkout\nconst order = await client.commerce.orders.checkout({\n cartId,\n orderNumber: 'ORD-240101-002',\n customerSnapshot: { email: 'user@example.com' },\n pgPaymentId: 'pay_xxx'\n})\n\\`\\`\\``,\n\n 'return-refund': `## Return & Refund Flow\n\n### Option A: Simple Return (return request only)\n1. **Create Return** → \\`create-return\\` tool\n - Order must be \\`delivered\\` or \\`confirmed\\`\n - Specify returnItems and refundAmount\n - Return status: requested → processing → approved → completed\n\n### Option B: Return + Refund (atomic, recommended)\n1. **Return with Refund** → \\`return-with-refund\\` tool\n - Handles return + stock restoration + transaction update in one call\n - Return immediately completed (bypasses FSM)\n - Requires pgPaymentId and paymentKey for provider-verified refund\n\n### Key Points\n- Full refund: original transaction → \\`canceled\\`\n- Partial refund: new refund transaction created\n- Stock restored: stock += qty, reservedStock -= qty\n- Cumulative refunds tracked: refundAmount + order.refundedAmount ≤ totalAmount\n- Cannot use \\`update-order\\` to set return-related statuses (must use return endpoints)\n\n### Code Example (Return with Refund)\n\\`\\`\\`typescript\nawait client.commerce.orders.returnWithRefund({\n orderNumber: 'ORD-240101-001',\n reason: 'defective',\n reasonDetail: 'Product arrived damaged',\n returnItems: [{ orderItem: 'oi-id', quantity: 1 }],\n refundAmount: 29900,\n pgPaymentId: 'pay_xxx',\n paymentKey: 'payment_key_xxx'\n})\n\\`\\`\\``,\n\n 'fulfillment-tracking': `## Fulfillment & Tracking\n\n### Creating Fulfillment\n1. **Create Fulfillment** → \\`create-fulfillment\\` tool\n - Order must be \\`paid\\` or \\`preparing\\`\n - With carrier + trackingNumber → fulfillment status = \\`shipped\\`\n - Without → fulfillment status = \\`pending\\`\n\n### Updating Fulfillment\n2. **Update** → \\`update-fulfillment\\` tool\n - FSM: pending → packed → shipped → delivered (terminal)\n - Or: pending/packed/shipped → failed (terminal)\n - Carrier/trackingNumber changeable only in pending/packed status\n\n### Auto Timestamps\n- \\`shipped\\` → sets \\`shippedAt\\`\n- \\`delivered\\` → sets \\`deliveredAt\\`\n\n### Order Auto-sync\n- All items shipped with carrier → order \\`shipped\\`\n- Partial shipment → order \\`preparing\\`\n- All non-failed fulfillments delivered → order \\`delivered\\`\n\n### Carriers\ncj, hanjin, lotte, epost, logen, other\n\n### Code Example\n\\`\\`\\`typescript\n// Create fulfillment with tracking\nawait client.commerce.orders.createFulfillment({\n orderNumber: 'ORD-240101-001',\n carrier: 'cj',\n trackingNumber: '1234567890',\n items: [{ orderItem: 'oi-id', quantity: 2 }]\n})\n\n// Mark as delivered\nawait client.commerce.orders.updateFulfillment({\n fulfillmentId: 'ful-id',\n status: 'delivered'\n})\n\\`\\`\\``,\n}\n\nexport default function orderFlowGuide({\n scenario,\n}: InferSchema<typeof schema>) {\n return `# Ecommerce Order Flow Guide: ${scenario}\n\n${SCENARIOS[scenario] || 'Unknown scenario.'}\n\n## Related MCP Tools\n- \\`create-order\\`, \\`get-order\\`, \\`update-order\\`\n- \\`checkout\\`\n- \\`create-fulfillment\\`, \\`update-fulfillment\\`\n- \\`create-return\\`, \\`update-return\\`, \\`return-with-refund\\`\n- \\`update-transaction\\`\n- \\`validate-discount\\`, \\`calculate-shipping\\``\n}\n","import { z } from 'zod'\nimport { type PromptMetadata, type InferSchema } from '../types'\n\nexport const schema = {\n feature: z\n .enum([\n 'ecommerce',\n 'customers',\n 'articles',\n 'documents',\n 'playlists',\n 'galleries',\n 'links',\n 'canvas',\n 'videos',\n 'live-streaming',\n 'forms',\n 'community',\n ])\n .describe('Feature to get setup guide for'),\n} as const\n\nexport const metadata: PromptMetadata = {\n name: 'feature-setup-guide',\n title: 'Feature Setup Guide',\n description:\n 'Setup checklist and remediation guide for a tenant feature. Load with check-feature-progress and get-tenant-context to diagnose setup gaps.',\n role: 'assistant',\n}\n\nconst FEATURES: Record<string, string> = {\n ecommerce: `## Ecommerce Setup Guide\n\n**Dependency**: \\`customers\\` feature must also be enabled.\n\n### Required Collections (count > 0)\n\n1. **products** — Create via Console UI or SDK \\`client.collections.from('products').create({ ... })\\`\n - Minimum fields: \\`{ title, slug, status: 'published' }\\`\n\n2. **product-variants** — At least 1 sellable variant per product\n - Minimum fields: \\`{ product, title, price, stock }\\`\n\n3. **shipping-policies** — At least 1 default policy required\n - Minimum fields: \\`{ title, baseFee, freeShippingThreshold, isDefault: true }\\`\n\n### System Collections (auto-created, count 0 is normal)\n\norders, order-items, transactions, fulfillments, fulfillment-items, returns, return-items, carts, cart-items\n\n### Optional Collections\n\nproduct-options, product-option-values, product-categories, product-tags, product-collections, brands, brand-logos, discounts\n\n### Config\n\n- **Webhook URL** must be configured in tenant settings for payment gateway callbacks\n- Use \\`check-feature-progress\\` for the tenant-aware ecommerce progress check\n- Use \\`get-tenant-context\\` to check current webhook configuration`,\n\n customers: `## Customers Setup Guide\n\n### Required Collections (count > 0)\n\n1. **customers** — At least 1 registered customer\n - Customers self-register via SDK \\`client.customer.register()\\`\n\n### System Collections (auto-created, count 0 is normal)\n\ncustomer-addresses\n\n### Optional Collections\n\n- customer-groups — Console/server-scoped segmentation for VIP coupons and campaigns. Use \\`createServerClient().collections.from('customer-groups')\\`.\n- customer-profile-lists — Public profile display/ranking lists for storefronts. Browser reads may use \\`client.collections.from('customer-profile-lists')\\`.\n\n### Config\n\n- Customer registration creates a local account; add app-level verification if needed\n- Customer auth uses custom JWT (separate from Payload auth)`,\n\n articles: `## Articles Setup Guide\n\n### Required Collections (count > 0)\n\n1. **articles** — At least 1 article\n - Minimum fields: \\`{ title, slug, status: 'published' }\\`\n\n2. **article-authors** — At least 1 author\n - Minimum fields: \\`{ title, slug, status: 'published' }\\`\n - Link authors to articles via the \\`authors\\` relationship field\n\n### Optional Collections\n\narticle-categories, article-tags`,\n\n documents: `## Documents Setup Guide\n\n### Required Collections (count > 0)\n\n1. **documents** — At least 1 document\n - Minimum fields: \\`{ title, slug }\\`\n\n2. **document-types** — At least 1 type\n - Minimum fields: \\`{ title, slug }\\`\n - Link document type via \\`type\\` relationship field\n\n### Optional Collections\n\ndocument-categories`,\n\n playlists: `## Playlists Setup Guide\n\n### Required Collections (count > 0)\n\n1. **playlists** — At least 1 playlist\n - Minimum fields: \\`{ title, slug, status: 'published' }\\`\n\n2. **tracks** — At least 1 track\n - Minimum fields: \\`{ title, sourceUrl, status: 'published' }\\`\n\n3. **playlists.tracks** — Link at least 1 track from a playlist\n - Minimum fields: \\`{ tracks: [trackId] }\\`\n\n### Optional Collections\n\nplaylist-categories, playlist-tags, track-categories, track-tags, track-assets`,\n\n galleries: `## Galleries Setup Guide\n\n### Required Collections (count > 0)\n\n1. **galleries** — At least 1 gallery\n - Minimum fields: \\`{ title, slug, status: 'published' }\\`\n\n2. **gallery-items** — At least 1 item per gallery\n - References \\`images\\` collection (non-upload)\n - Minimum fields: \\`{ gallery, image, status: 'published' }\\`\n\n### Optional Collections\n\ngallery-categories, gallery-tags`,\n\n links: `## Links Setup Guide\n\n### Required Collections (count > 0)\n\n1. **links** — At least 1 link\n - Minimum fields: \\`{ title, slug, url, status: 'published' }\\`\n\n### Optional Collections\n\nlink-categories, link-tags`,\n\n canvas: `## Canvas Setup Guide\n\n### Required Collections (count > 0)\n\n1. **canvases** — At least 1 canvas\n - Minimum fields: \\`{ title, slug }\\`\n - \\`canvas\\` field holds React Flow JSON data\n\n### Optional Collections\n\ncanvas-node-types, canvas-edge-types, canvas-categories, canvas-tags`,\n\n videos: `## Videos Setup Guide\n\n**Config**: Mux integration required — \\`MUX_TOKEN_ID\\` env var must be set on the server.\n\n### Required Collections (count > 0)\n\n1. **videos** — At least 1 uploaded video\n - Videos are uploaded via the Console upload endpoint\n - Mux metadata (assetId, playbackId) is auto-populated after upload\n\n### Optional Collections\n\nvideo-categories, video-tags`,\n\n 'live-streaming': `## Live Streaming Setup Guide\n\n**Config**: Mux integration required — \\`MUX_TOKEN_ID\\` env var must be set on the server.\n\n### Required Collections (count > 0)\n\n1. **live-streams** — At least 1 stream created\n - Minimum fields: \\`{ title, slug }\\`\n - \\`streamKey\\` is hidden and auto-generated by Mux\n - 6 endpoints available: create, stream-key, reset-key, complete, disable, enable\n\n### Plan Requirement\n\nLive streaming is Enterprise-only. Verify tenant plan before setup.`,\n\n forms: `## Forms Setup Guide\n\n### Required Collections (count > 0)\n\n1. **forms** — At least 1 form\n - Minimum fields: \\`{ title }\\`\n - Built on Payload Forms Plugin\n\n### System Collections (auto-created, count 0 is normal)\n\nform-submissions — Auto-created when forms are submitted by end users`,\n\n community: `## Community Setup Guide\n\n**Dependency**: \\`customers\\` feature must also be enabled (customers are community members).\n\n### Required Collections (count > 0)\n\n1. **posts** — At least 1 post\n - Minimum fields: \\`{ title, slug }\\`\n\n2. **reaction-types** — At least 1 reaction type defined\n - Minimum fields: \\`{ title }\\` (e.g. \"Like\", \"Love\", \"Haha\")\n\n### System Collections (auto-created, count 0 is normal)\n\ncomments, reactions, bookmarks, reports, community-bans\n\n### Optional Collections\n\npost-categories, customer-profile-lists`,\n}\n\nexport default function featureSetupGuide({\n feature,\n}: InferSchema<typeof schema>) {\n return `# Feature Setup Guide: ${feature}\n\n${FEATURES[feature] || 'Unknown feature.'}\n\n## Related MCP Tools\n- \\`check-feature-progress\\` — run the tenant-aware ecommerce implementation progress check\n- \\`get-tenant-context\\` — check current collection counts and feature status\n- \\`query-collection\\` — verify existing documents in a collection\n- \\`get-collection-schema\\` — inspect tenant-aware fields before creating data via SDK or Console UI`\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'app-config',\n title: 'Application Config',\n description: '01.software SDK and MCP server configuration information',\n}\n\nexport default function handler() {\n return `# 01.software MCP Server Configuration\n\n## Server Info\n- **Name**: 01.software MCP Server\n- **Version**: 0.1.0\n- **Hosted transport**: HTTP (Streamable)\n- **Local transport**: stdio through \\`npx @01.software/cli mcp\\`\n\n## Authentication\n\nHTTP MCP uses OAuth discovery and Authorization Code + PKCE.\n\n\\`\\`\\`toml\n[mcp_servers.01software]\nurl = \"https://mcp.01.software/mcp\"\n\\`\\`\\`\n\n## Hosted HTTP OAuth Tools (9)\n\nThe hosted HTTP MCP endpoint at https://mcp.01.software/mcp exposes only these OAuth-safe tools:\n\n### Schema (1)\n- \\`get-collection-schema\\` - Get authoritative tenant-aware collection schema\n\n### Tenant Context (2)\n- \\`get-tenant-context\\` - Get tenant features, active collections, and field config\n- \\`check-feature-progress\\` - Check ecommerce implementation progress without mutating tenant data\n\n### Field Config (2)\n- \\`list-configurable-fields\\` - List configurable fields and current hidden state\n- \\`update-field-config\\` - Update hidden collections and fields for the current tenant\n\n### Guidance (4)\n- \\`sdk-get-recipe\\` - Get SDK recipe for a concrete task\n- \\`sdk-search-docs\\` - Search SDK documentation\n- \\`sdk-get-auth-setup\\` - Get framework-specific auth setup guidance\n- \\`sdk-get-collection-pattern\\` - Get collection-specific usage patterns\n\n## Local CLI Stdio Surface (30)\n\nFor trusted local server-key workflows, start the stdio server:\n\n\\`\\`\\`bash\nnpx @01.software/cli mcp\n\\`\\`\\`\n\nLocal stdio can expose generic read, order, return, cart, validation, stock, schema, tenant context, feature progress, field config, and guidance tools. Generic collection write tools (create/update/delete/update-many/delete-many) are intentionally absent on every transport; use the SDK server client for generic writes.\n\n## Rate Limits\n\nRate limits depend on your tenant plan:\n- **Free**: 500,000 API calls/month\n- **Starter**: 500,000 API calls/month\n- **Basic**: 2,000,000 API calls/month\n- **Pro**: 5,000,000 API calls/month\n- **Enterprise**: Unlimited`\n}\n","import { type ResourceMetadata } from '../../types'\nimport { COLLECTIONS } from '@01.software/sdk'\n\nexport const schema = {} as const\n\nexport const metadata: ResourceMetadata = {\n name: 'collections-schema',\n title: 'Collection Schema Info',\n description: 'Available collections and their schema information',\n}\n\nexport const COLLECTIONS_BY_CATEGORY = {\n 'Tenant Management': ['tenants', 'tenant-metadata', 'tenant-logos'],\n Products: [\n 'products',\n 'product-variants',\n 'product-options',\n 'product-option-values',\n 'product-categories',\n 'product-tags',\n 'product-collections',\n ],\n Brands: ['brands', 'brand-logos'],\n 'Orders & Fulfillment': [\n 'orders',\n 'order-items',\n 'transactions',\n 'fulfillments',\n 'fulfillment-items',\n ],\n 'Shipping & Returns': [\n 'returns',\n 'return-items',\n 'shipping-policies',\n 'shipping-zones',\n ],\n Customers: [\n 'customers',\n 'customer-profiles',\n 'customer-profile-lists',\n 'customer-addresses',\n ],\n Carts: ['carts', 'cart-items'],\n Discounts: ['discounts'],\n Documents: ['documents', 'document-categories', 'document-types'],\n Articles: [\n 'articles',\n 'article-authors',\n 'article-categories',\n 'article-tags',\n ],\n Community: [\n 'posts',\n 'comments',\n 'reactions',\n 'reaction-types',\n 'bookmarks',\n 'post-categories',\n ],\n Playlists: [\n 'playlists',\n 'tracks',\n 'playlist-categories',\n 'playlist-tags',\n 'track-categories',\n 'track-tags',\n ],\n Galleries: [\n 'galleries',\n 'gallery-items',\n 'gallery-categories',\n 'gallery-tags',\n ],\n Links: ['links', 'link-categories', 'link-tags'],\n Canvas: [\n 'canvases',\n 'canvas-node-types',\n 'canvas-edge-types',\n 'canvas-categories',\n 'canvas-tags',\n 'canvas-nodes',\n 'canvas-edges',\n ],\n Videos: ['videos', 'video-categories', 'video-tags'],\n 'Live Streams': ['live-streams'],\n Images: ['images'],\n Forms: ['forms', 'form-submissions'],\n Events: [\n 'event-calendars',\n 'events',\n 'event-categories',\n 'event-occurrences',\n 'event-tags',\n ],\n} as const satisfies Record<string, readonly string[]>\n\nexport default function handler() {\n const categoryDocs = Object.entries(COLLECTIONS_BY_CATEGORY)\n .map(([category, collections]) => {\n const collectionList = collections\n .filter((c) => COLLECTIONS.includes(c as (typeof COLLECTIONS)[number]))\n .map((c) => `- **${c}**`)\n .join('\\n')\n return `## ${category}\\n${collectionList}`\n })\n .join('\\n\\n')\n\n return `# Available Collections\n\nCollections accessible via the 01.software SDK:\n\n${categoryDocs}\n\n## Supported Operations\n\nEach collection supports the following operations:\n- \\`find(options?)\\` - Query list with filtering, sorting, pagination\n- \\`findById(id)\\` - Get single item by ID\n- \\`create(data)\\` - Create new item\n- \\`update(id, data)\\` - Update existing item\n- \\`remove(id)\\` - Delete item\n- \\`updateMany(where, data)\\` - Bulk update items matching filter\n- \\`removeMany(where)\\` - Bulk delete items matching filter\n\nStatus-managed public collections expose only \\`status: 'published'\\` rows to\npublishable-key reads unless server-side access explicitly includes\nunpublished statuses.\n\n## Query Examples\n\n### Filtering\n\\`\\`\\`json\n{\n \"where\": {\n \"status\": { \"equals\": \"published\" },\n \"price\": { \"greater_than\": 1000 }\n }\n}\n\\`\\`\\`\n\n### Pagination & Sorting\n\\`\\`\\`json\n{\n \"limit\": 10,\n \"page\": 1,\n \"sort\": \"-createdAt\"\n}\n\\`\\`\\`\n\nTotal available collections: ${COLLECTIONS.length}`\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-getting-started',\n title: 'Getting Started',\n description: '01.software SDK getting started guide',\n}\n\nexport default function handler() {\n return `# Getting Started\n\nA guide to getting started with the 01.software SDK.\n\n## Installation\n\n\\`\\`\\`bash\nnpm install @01.software/sdk\n# or\nyarn add @01.software/sdk\n# or\npnpm add @01.software/sdk\n\\`\\`\\`\n\n## Basic Usage\n\n\\`\\`\\`typescript\nimport { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!\n})\n\n// Query data\nconst result = await client.collections.from('products').find({\n where: { status: { equals: 'published' } },\n limit: 10\n})\n// result.docs - array of products\n\\`\\`\\`\n\n## Next Steps\n\n- [SDK Guide](/developers/sdk) - Install and query workspace content\n- [Authentication & Keys](/developers/authentication) - Choose the right key for each surface\n- [API](/developers/api) - Use the HTTP API when SDKs are not a fit`\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-guides',\n title: 'Guides',\n description: '01.software SDK usage guides',\n}\n\nexport default function handler() {\n return `# Guides\n\nComprehensive guides to master the 01.software SDK.\n\n## Data Fetching\n\nUse the Query Builder or React Query hooks to fetch data efficiently.\n\n### Query Builder\n\\`\\`\\`typescript\n// Basic query\nconst result = await client.collections.from('products').find({ limit: 10 })\n\n// With filters\nconst result = await client.collections.from('products').find({\n where: {\n status: { equals: 'published' },\n 'listing.minPrice': { greater_than: 1000 },\n },\n sort: '-createdAt',\n limit: 20,\n page: 1,\n})\n// result.docs, result.totalDocs, result.hasNextPage, ...\n\n// Single item\nconst product = await client.collections.from('products').findById('product-id')\n\n// Count\nconst { totalDocs } = await client.collections.from('products').count()\n\\`\\`\\`\n\n### React Query Hook\n\\`\\`\\`typescript\nconst { data, isLoading, error } = client.query.useQuery({\n collection: 'products',\n options: {\n where: { status: { equals: 'published' } },\n limit: 10\n }\n})\n\\`\\`\\`\n\n### Suspense Mode\n\\`\\`\\`typescript\nconst { data } = client.query.useSuspenseQuery({\n collection: 'products',\n options: { limit: 10 }\n})\n\\`\\`\\`\n\n### Infinite Scroll\n\\`\\`\\`typescript\nconst { data, fetchNextPage, hasNextPage, isFetchingNextPage } =\n client.query.useInfiniteQuery({\n collection: 'products',\n pageSize: 20\n })\n\\`\\`\\`\n\n## Mutations & Updates\n\nServerClient is required for write operations.\n\n### Create\n\\`\\`\\`typescript\nconst result = await serverClient.from('products').create({\n title: 'New Product',\n status: 'draft'\n})\n// result.doc - created document, result.message\n\\`\\`\\`\n\n### Update\n\\`\\`\\`typescript\nconst result = await serverClient.from('products').update('product-id', {\n title: 'Updated Title'\n})\n// Partial updates supported - only changed fields needed\n\\`\\`\\`\n\n### Delete\n\\`\\`\\`typescript\nconst deleted = await serverClient.from('products').remove('product-id')\n// Returns the deleted document directly\n\\`\\`\\`\n\n### Bulk Operations\n\\`\\`\\`typescript\n// Update all matching documents\nconst result = await serverClient.from('products').updateMany(\n { status: { equals: 'draft' } },\n { status: 'published' }\n)\n\n// Delete all matching documents\nconst result = await serverClient.from('products').removeMany(\n { status: { equals: 'archived' } }\n)\n\\`\\`\\`\n\n### Mutation Hooks (React)\n\\`\\`\\`typescript\n// Create with auto cache invalidation\nconst { mutate: create } = client.query.useCreate({ collection: 'products' })\ncreate({ title: 'New', status: 'draft' })\n\n// Update with auto cache invalidation\nconst { mutate: update } = client.query.useUpdate({ collection: 'products' })\nupdate({ id: 'product-id', data: { title: 'Updated' } })\n\n// Remove with auto cache invalidation\nconst { mutate: remove } = client.query.useRemove({ collection: 'products' })\nremove('product-id')\n\\`\\`\\`\n\n## Caching Strategies\n\nThe SDK uses React Query for caching and background updates.\n\n### SSR Prefetching\n\\`\\`\\`typescript\n// Prefetch in server component for instant client hydration\nawait client.query.prefetchQuery({\n collection: 'products',\n options: { limit: 10 }\n})\n\nawait client.query.prefetchQueryById({\n collection: 'products',\n id: 'product-id'\n})\n\nawait client.query.prefetchInfiniteQuery({\n collection: 'products',\n pageSize: 20\n})\n\\`\\`\\`\n\n### Cache Invalidation\n\\`\\`\\`typescript\n// Invalidate list cache for a collection\nclient.query.invalidateQueries('products', 'list')\n\n// Invalidate all caches for a collection\nclient.query.invalidateQueries('products')\n\\`\\`\\`\n\n### Manual Cache Management\n\\`\\`\\`typescript\n// Read cached data\nconst cached = client.query.getQueryData('products', 'list')\n\n// Write to cache (optimistic updates)\nclient.query.setQueryData('products', 'list', newData)\n\\`\\`\\`\n\n## Error Handling\n\n\\`\\`\\`typescript\ntry {\n const result = await client.collections.from('products').find()\n console.log(result.docs)\n} catch (error) {\n if (error instanceof Error) {\n console.error('API Error:', error.message)\n }\n}\n\\`\\`\\`\n\n## Filtering Reference\n\nPayload query syntax operators:\n\n| Operator | Description | Example |\n|----------|-------------|---------|\n| \\`equals\\` | Exact match | \\`{ status: { equals: 'published' } }\\` |\n| \\`not_equals\\` | Not equal | \\`{ status: { not_equals: 'draft' } }\\` |\n| \\`greater_than\\` | Greater than | \\`{ 'listing.minPrice': { greater_than: 1000 } }\\` |\n| \\`less_than\\` | Less than | \\`{ 'listing.minPrice': { less_than: 5000 } }\\` |\n| \\`contains\\` | String contains | \\`{ title: { contains: 'phone' } }\\` |\n| \\`like\\` | Pattern match | \\`{ title: { like: '%phone%' } }\\` |\n| \\`in\\` | In array | \\`{ status: { in: ['published', 'draft'] } }\\` |\n| \\`exists\\` | Field exists | \\`{ image: { exists: true } }\\` |\n\n### Logical Operators\n\\`\\`\\`typescript\n{\n or: [\n { category: { equals: 'electronics' } },\n { featured: { equals: true } }\n ],\n and: [\n { 'listing.minPrice': { greater_than: 1000 } },\n { 'listing.minPrice': { less_than: 5000 } }\n ]\n}\n\\`\\`\\`\n\nFor ecommerce collections, \\`products.listing.*\\` is the browse/search projection. Authoritative sellable price and stock remain on \\`product-variants\\`.\n\nFor more implementation guidance, see the [SDK Guide](/developers/sdk).`\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-api',\n title: 'API Reference',\n description: '01.software SDK API reference documentation',\n}\n\nexport default function handler() {\n return `# API Reference\n\nComprehensive documentation for all methods and types in the 01.software SDK.\n\n## Client Types\n\n### Client\nFor client-side React applications (read-only)\n\n\\`\\`\\`typescript\nimport { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: string\n})\n\\`\\`\\`\n\n### ServerClient\nFor server-side operations (full CRUD)\n\n\\`\\`\\`typescript\nimport { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: string,\n secretKey: string\n})\n\\`\\`\\`\n\n## Query Builder API (client.collections.from)\n\n### find()\nQuery documents from a collection.\n\n\\`\\`\\`typescript\nconst result = await client.collections.from('collection').find({\n where?: object, // Payload query syntax\n limit?: number, // Items per page\n page?: number, // Page number (starts from 1)\n sort?: string // Sort field (\"-createdAt\" for descending)\n})\n// result.docs - array of documents\n// result.totalDocs, result.page, result.totalPages, result.hasNextPage, ...\n\\`\\`\\`\n\n### findById()\nGet a single item by ID.\n\n\\`\\`\\`typescript\nconst doc = await client.collections.from('collection').findById(id: string)\n// Returns the document directly\n\\`\\`\\`\n\n### count()\nCount documents in a collection.\n\n\\`\\`\\`typescript\nconst { totalDocs } = await client.collections.from('collection').count()\n\\`\\`\\`\n\n### create() (ServerClient only)\nCreate a new item.\n\n\\`\\`\\`typescript\nconst result = await client.collections.from('collection').create(data: object)\n// result.doc - created item, result.message\n\\`\\`\\`\n\n### update() (ServerClient only)\nUpdate an existing item.\n\n\\`\\`\\`typescript\nconst result = await client.collections.from('collection').update(id: string, data: object)\n// result.doc - updated item, result.message\n\\`\\`\\`\n\n### remove() (ServerClient only)\nDelete an item.\n\n\\`\\`\\`typescript\nconst doc = await client.collections.from('collection').remove(id: string)\n// Returns the deleted document directly\n\\`\\`\\`\n\n### updateMany() (ServerClient only)\nBulk update documents matching a filter.\n\n\\`\\`\\`typescript\nconst result = await client.collections.from('collection').updateMany(where, data)\n// Returns PayloadFindResponse with updated docs\n\\`\\`\\`\n\n### removeMany() (ServerClient only)\nBulk delete documents matching a filter.\n\n\\`\\`\\`typescript\nconst result = await client.collections.from('collection').removeMany(where)\n// Returns PayloadFindResponse with deleted docs\n\\`\\`\\`\n\n## React Query Hooks (client.query)\n\n### useQuery()\nQuery a collection list.\n\n\\`\\`\\`typescript\nconst { data, isLoading, error } = client.query.useQuery({\n collection: 'products',\n options: { limit: 10, where: { status: { equals: 'published' } } }\n})\n\\`\\`\\`\n\n### useSuspenseQuery()\nSuspense mode list query.\n\n\\`\\`\\`typescript\nconst { data } = client.query.useSuspenseQuery({\n collection: 'products',\n options: { limit: 10 }\n})\n\\`\\`\\`\n\n### useQueryById()\nGet a single item by ID.\n\n\\`\\`\\`typescript\nconst { data } = client.query.useQueryById({\n collection: 'products',\n id: 'product-id'\n})\n\\`\\`\\`\n\n### useSuspenseQueryById()\nSuspense mode single item query.\n\n\\`\\`\\`typescript\nconst { data } = client.query.useSuspenseQueryById({\n collection: 'products',\n id: 'product-id'\n})\n\\`\\`\\`\n\n### useInfiniteQuery()\nInfinite scroll.\n\n\\`\\`\\`typescript\nconst { data, fetchNextPage, hasNextPage } = client.query.useInfiniteQuery({\n collection: 'products',\n options: { limit: 20 },\n pageSize: 20\n})\n\\`\\`\\`\n\n### useSuspenseInfiniteQuery()\nSuspense mode infinite scroll.\n\n\\`\\`\\`typescript\nconst { data, fetchNextPage } = client.query.useSuspenseInfiniteQuery({\n collection: 'products',\n pageSize: 20\n})\n\\`\\`\\`\n\n## Mutation Hooks (client.query)\n\n### useCreate()\nCreate a document with automatic cache invalidation.\n\n\\`\\`\\`typescript\nconst { mutate } = client.query.useCreate({ collection: 'products' })\nmutate({ title: 'New Product', status: 'draft' })\n\\`\\`\\`\n\n### useUpdate()\nUpdate a document with automatic cache invalidation.\n\n\\`\\`\\`typescript\nconst { mutate } = client.query.useUpdate({ collection: 'products' })\nmutate({ id: 'product-id', data: { title: 'Updated' } })\n\\`\\`\\`\n\n### useRemove()\nRemove a document with automatic cache invalidation.\n\n\\`\\`\\`typescript\nconst { mutate } = client.query.useRemove({ collection: 'products' })\nmutate('product-id')\n\\`\\`\\`\n\n## Cache Utilities\n\n\\`\\`\\`typescript\n// Invalidate cache\nclient.query.invalidateQueries('products', 'list')\n\n// SSR prefetch\nawait client.query.prefetchQuery({ collection: 'products', options: { limit: 10 } })\nawait client.query.prefetchQueryById({ collection: 'products', id: 'id' })\nawait client.query.prefetchInfiniteQuery({ collection: 'products', pageSize: 20 })\n\n// Get/set cached data\nconst cached = client.query.getQueryData('products', 'list')\nclient.query.setQueryData('products', 'list', newData)\n\\`\\`\\`\n\nFor ecommerce reads, prefer \\`products.listing.*\\` for card/search pricing and keep authoritative sellable pricing on \\`product-variants.price\\`.\n\n## Customer Auth API (Client only)\n\nCustomer authentication and profile management. Available on \\`Client\\` only (\\`client.customer\\`).\n\n### Authentication\n\\`\\`\\`typescript\n// Register\nconst { customer } = await client.customer.register({\n name: 'John',\n email: 'john@example.com',\n password: 'password123',\n phone?: '+821012345678'\n})\n\n// Login\nconst { token, customer } = await client.customer.login({\n email: 'john@example.com',\n password: 'password123'\n})\n\n// Refresh token\nconst { token } = await client.customer.refreshToken()\n\n// Logout\nclient.customer.logout()\n\\`\\`\\`\n\n### Profile\n\\`\\`\\`typescript\n// Get current customer\nconst profile = await client.customer.me()\n\n// Update profile (name, phone, marketingConsent only)\nconst updated = await client.customer.updateProfile({\n name?: 'New Name',\n phone?: '+821098765432',\n marketingConsent?: true\n})\n\\`\\`\\`\n\n### Password\n\\`\\`\\`typescript\n// Forgot password (sends reset token to configured tenant webhooks)\nawait client.customer.forgotPassword(email)\n\n// Reset password with token\nawait client.customer.resetPassword(token, newPassword)\n\n// Change password (requires current password)\nawait client.customer.changePassword(currentPassword, newPassword)\n\\`\\`\\`\n\n### Orders\n\\`\\`\\`typescript\nconst orders = await client.commerce.orders.listMine({\n page: 1,\n limit: 10,\n status: 'paid'\n})\n\\`\\`\\`\n\n### Token Management\n\\`\\`\\`typescript\nclient.customer.getToken() // Get current JWT\nclient.customer.setToken(token) // Set JWT manually\nclient.customer.isAuthenticated() // Check auth status\nclient.customer.logout() // Clear token\n\\`\\`\\`\n\nFor more details, see the [API documentation](/developers/api).`\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-query-builder',\n title: 'Query Builder',\n description: '01.software SDK Query Builder API reference (client.collections.from)',\n}\n\nexport default function handler() {\n return `# Query Builder API\n\nThe Query Builder provides a fluent interface for querying collections via \\`client.collections.from(collection)\\`.\n\n## Methods\n\n### find()\nQuery documents from a collection.\n\n\\`\\`\\`typescript\nconst result = await client.collections.from('products').find({\n where?: object, // Payload query syntax\n limit?: number, // Items per page (default: 10)\n page?: number, // Page number (starts from 1)\n sort?: string, // Sort field (\"-createdAt\" for descending)\n depth?: number, // Relationship depth\n})\n\n// Return type: PayloadFindResponse\n// result.docs - array of documents\n// result.totalDocs - total matching document count\n// result.page - current page\n// result.totalPages - total pages\n// result.hasNextPage - whether next page exists\n// result.hasPrevPage - whether previous page exists\n// result.nextPage - next page number (null if none)\n// result.prevPage - previous page number (null if none)\n\\`\\`\\`\n\n### findById()\nGet a single document by ID.\n\n\\`\\`\\`typescript\nconst doc = await client.collections.from('products').findById('product-id')\n// Returns the document directly (not wrapped)\n\\`\\`\\`\n\n### count()\nCount documents matching an optional filter.\n\n\\`\\`\\`typescript\nconst { totalDocs } = await client.collections.from('products').count({\n where?: object\n})\n\\`\\`\\`\n\n### create() — ServerClient only\nCreate a new document.\n\n\\`\\`\\`typescript\nconst result = await serverClient.from('products').create({\n title: 'New Product',\n price: 29900,\n status: 'draft',\n})\n// result.doc - created document\n// result.message - success message\n\\`\\`\\`\n\n### update() — ServerClient only\nUpdate an existing document (partial updates supported).\n\n\\`\\`\\`typescript\nconst result = await serverClient.from('products').update('product-id', {\n title: 'Updated Title',\n})\n// result.doc - updated document\n// result.message - success message\n\\`\\`\\`\n\n### remove() — ServerClient only\nDelete a document by ID.\n\n\\`\\`\\`typescript\nconst doc = await serverClient.from('products').remove('product-id')\n// Returns the deleted document directly\n\\`\\`\\`\n\n### updateMany() — ServerClient only\nBulk update documents matching a filter.\n\n\\`\\`\\`typescript\nconst result = await serverClient.from('products').updateMany(\n { status: { equals: 'draft' } }, // where\n { status: 'published' } // data\n)\n// Returns PayloadFindResponse with updated docs\n\\`\\`\\`\n\n### removeMany() — ServerClient only\nBulk delete documents matching a filter.\n\n\\`\\`\\`typescript\nconst result = await serverClient.from('products').removeMany(\n { status: { equals: 'archived' } } // where\n)\n// Returns PayloadFindResponse with deleted docs\n\\`\\`\\`\n\n## Filtering Reference\n\nPayload query syntax operators:\n\n| Operator | Description | Example |\n|----------|-------------|---------|\n| \\`equals\\` | Exact match | \\`{ status: { equals: 'published' } }\\` |\n| \\`not_equals\\` | Not equal | \\`{ status: { not_equals: 'draft' } }\\` |\n| \\`greater_than\\` | Greater than | \\`{ 'listing.minPrice': { greater_than: 1000 } }\\` |\n| \\`less_than\\` | Less than | \\`{ 'listing.minPrice': { less_than: 5000 } }\\` |\n| \\`greater_than_equal\\` | Greater than or equal | \\`{ 'listing.minPrice': { greater_than_equal: 1000 } }\\` |\n| \\`less_than_equal\\` | Less than or equal | \\`{ 'listing.minPrice': { less_than_equal: 5000 } }\\` |\n| \\`contains\\` | String contains | \\`{ title: { contains: 'phone' } }\\` |\n| \\`like\\` | Pattern match | \\`{ title: { like: '%phone%' } }\\` |\n| \\`in\\` | In array | \\`{ status: { in: ['published', 'draft'] } }\\` |\n| \\`not_in\\` | Not in array | \\`{ status: { not_in: ['archived'] } }\\` |\n| \\`exists\\` | Field exists | \\`{ image: { exists: true } }\\` |\n\n## Logical Operators\n\n\\`\\`\\`typescript\nconst result = await client.collections.from('products').find({\n where: {\n or: [\n { category: { equals: 'electronics' } },\n { isFeatured: { equals: true } },\n ],\n and: [\n { 'listing.minPrice': { greater_than: 1000 } },\n { 'listing.minPrice': { less_than: 50000 } },\n ],\n },\n})\n\\`\\`\\`\n\n## Pagination\n\n\\`\\`\\`typescript\n// Page-based pagination\nconst page1 = await client.collections.from('products').find({ limit: 20, page: 1 })\nconst page2 = await client.collections.from('products').find({ limit: 20, page: 2 })\n\n// Check if more pages exist\nif (page1.hasNextPage) {\n // fetch page1.nextPage\n}\n\\`\\`\\`\n\n## Sorting\n\n\\`\\`\\`typescript\n// Descending (newest first)\nconst result = await client.collections.from('articles').find({ sort: '-createdAt' })\n\n// Ascending\nconst result2 = await client.collections.from('products').find({ sort: 'price' })\n\n// Multiple fields (comma-separated)\nconst result3 = await client.collections.from('products').find({ sort: '-isFeatured,title' })\n\\`\\`\\`\n\n## Full Example\n\n\\`\\`\\`typescript\nimport { createServerClient } from '@01.software/sdk'\n\nconst serverClient = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// Find published products, sorted by newest, page 1\nconst result = await serverClient.from('products').find({\n where: {\n status: { equals: 'published' },\n price: { greater_than: 0 },\n },\n sort: '-createdAt',\n limit: 20,\n page: 1,\n})\n\nconsole.log(result.docs) // Product[]\nconsole.log(result.totalDocs) // e.g. 142\nconsole.log(result.hasNextPage) // true\n\\`\\`\\``\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-react-query',\n title: 'React Query Hooks',\n description: '01.software SDK React Query hooks reference (client.query)',\n}\n\nexport default function handler() {\n return `# React Query Hooks\n\nReact Query hooks are available on the browser-side \\`Client\\` via \\`client.query\\`. They provide automatic caching, background refetching, and cache invalidation.\n\n> React Query hooks are available on \\`Client\\` (createClient) only. \\`ServerClient\\` does not include them.\n\n## Query Hooks\n\n### useQuery()\nQuery a collection list with automatic caching.\n\n\\`\\`\\`typescript\nconst { data, isLoading, error } = client.query.useQuery({\n collection: 'products',\n options: {\n where: { status: { equals: 'published' } },\n limit: 10,\n page: 1,\n sort: '-createdAt',\n },\n})\n// data: PayloadFindResponse | undefined\n// data.docs, data.totalDocs, data.hasNextPage, ...\n\\`\\`\\`\n\n### useSuspenseQuery()\nSuspense-mode list query. Throws a promise while loading (use with React Suspense boundary).\n\n\\`\\`\\`typescript\n// Inside a Suspense boundary\nconst { data } = client.query.useSuspenseQuery({\n collection: 'products',\n options: { limit: 10 },\n})\n// data is always defined (never undefined)\n\\`\\`\\`\n\n### useQueryById()\nGet a single document by ID.\n\n\\`\\`\\`typescript\nconst { data, isLoading } = client.query.useQueryById({\n collection: 'products',\n id: 'product-id',\n})\n// data: Product | undefined\n\\`\\`\\`\n\n### useSuspenseQueryById()\nSuspense-mode single document query.\n\n\\`\\`\\`typescript\nconst { data } = client.query.useSuspenseQueryById({\n collection: 'products',\n id: 'product-id',\n})\n// data is always defined\n\\`\\`\\`\n\n### useInfiniteQuery()\nInfinite scroll with automatic page management.\n\n\\`\\`\\`typescript\nconst {\n data,\n fetchNextPage,\n hasNextPage,\n isFetchingNextPage,\n} = client.query.useInfiniteQuery({\n collection: 'products',\n options: {\n where: { status: { equals: 'published' } },\n },\n pageSize: 20,\n})\n\n// data.pages - array of PayloadFindResponse\n// data.pages.flatMap(p => p.docs) - all loaded docs\n\\`\\`\\`\n\n### useSuspenseInfiniteQuery()\nSuspense-mode infinite scroll.\n\n\\`\\`\\`typescript\nconst { data, fetchNextPage, hasNextPage } = client.query.useSuspenseInfiniteQuery({\n collection: 'products',\n pageSize: 20,\n})\n\\`\\`\\`\n\n## Mutation Hooks\n\nMutation hooks automatically invalidate relevant cache keys after success.\n\n### useCreate()\nCreate a document and invalidate list cache.\n\n\\`\\`\\`typescript\nconst { mutate, mutateAsync, isPending } = client.query.useCreate({\n collection: 'products',\n})\n\n// Fire and forget\nmutate({ title: 'New Product', status: 'draft' })\n\n// Await result\nconst result = await mutateAsync({ title: 'New Product', status: 'draft' })\n// result.doc - created document\n\\`\\`\\`\n\nFor ecommerce reads, price-oriented product cards should consume \\`products.listing.minPrice/maxPrice\\`. Authoritative sellable pricing still lives on \\`product-variants.price\\`.\n\n### useUpdate()\nUpdate a document and invalidate list + detail cache.\n\n\\`\\`\\`typescript\nconst { mutate, mutateAsync } = client.query.useUpdate({\n collection: 'products',\n})\n\nmutate({ id: 'product-id', data: { title: 'Updated Title' } })\n\\`\\`\\`\n\n### useRemove()\nRemove a document and invalidate list cache.\n\n\\`\\`\\`typescript\nconst { mutate, mutateAsync } = client.query.useRemove({\n collection: 'products',\n})\n\nmutate('product-id')\n\\`\\`\\`\n\n## Cache Utilities\n\n### invalidateQueries()\nManually invalidate cached queries for a collection.\n\n\\`\\`\\`typescript\n// Invalidate all list queries for a collection\nclient.query.invalidateQueries('products', 'list')\n\n// Invalidate all queries for a collection (list + detail)\nclient.query.invalidateQueries('products')\n\\`\\`\\`\n\n### getQueryData() / setQueryData()\nRead and write the React Query cache directly.\n\n\\`\\`\\`typescript\n// Read cached data\nconst cached = client.query.getQueryData('products', 'list')\n\n// Write to cache (useful for optimistic updates)\nclient.query.setQueryData('products', 'list', newData)\n\\`\\`\\`\n\n## SSR Prefetching\n\nPrefetch data in server components for instant hydration on the client.\n\n\\`\\`\\`typescript\n// app/products/page.tsx (Next.js App Router Server Component)\nimport { HydrationBoundary, dehydrate } from '@tanstack/react-query'\nimport { createServerClient } from '@01.software/sdk'\n\nexport default async function ProductsPage() {\n const serverClient = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n })\n\n // Prefetch list\n await serverClient.query.prefetchQuery({\n collection: 'products',\n options: { limit: 20, where: { status: { equals: 'published' } } },\n })\n\n // Prefetch single item\n await serverClient.query.prefetchQueryById({\n collection: 'products',\n id: 'product-id',\n })\n\n // Prefetch infinite query\n await serverClient.query.prefetchInfiniteQuery({\n collection: 'products',\n pageSize: 20,\n })\n\n return (\n <HydrationBoundary state={dehydrate(serverClient.query.queryClient)}>\n <ProductList />\n </HydrationBoundary>\n )\n}\n\\`\\`\\`\n\n## Full Component Example\n\n\\`\\`\\`typescript\n'use client'\n\nimport { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n})\n\nexport function ProductList() {\n const { data, isLoading, error } = client.query.useQuery({\n collection: 'products',\n options: {\n where: { status: { equals: 'published' } },\n sort: '-createdAt',\n limit: 20,\n },\n })\n\n const { mutate: removeProduct } = client.query.useRemove({\n collection: 'products',\n })\n\n if (isLoading) return <div>Loading...</div>\n if (error) return <div>Error: {error.message}</div>\n\n return (\n <ul>\n {data?.docs.map((product) => (\n <li key={product.id}>\n {product.title}\n <button onClick={() => removeProduct(product.id)}>Delete</button>\n </li>\n ))}\n </ul>\n )\n}\n\\`\\`\\``\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-server-api',\n title: 'Server-side API',\n description:\n '01.software SDK server-side API reference (client.commerce) for orders, fulfillments, returns, carts, and validation',\n}\n\nexport default function handler() {\n return `# Server-side API\n\nServer-side operations are available via \\`client.commerce\\` on \\`ServerClient\\`. Use \\`createServerClient\\` with both \\`publishableKey\\` and \\`secretKey\\`.\n\n\\`\\`\\`typescript\nimport { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\\`\\`\\`\n\nUse server components, API routes, or server actions only. Never expose\n\\`SOFTWARE_SECRET_KEY\\` to browser code, client bundles, logs, or public\nrepositories. If a secret key leaks, rotate it from the Console before deploying\nagain.\n\n## Order API\n\n### createOrder()\nCreate an order directly (without a cart).\n\n\\`\\`\\`typescript\nconst order = await client.commerce.orders.create({\n orderNumber: 'ORD-20240101-0001',\n customerSnapshot: { name: 'John Doe', email: 'john@example.com', phone: '+821012345678' },\n customer?: 'customer-id',\n shippingAddress: {\n recipientName: 'John Doe',\n phone: '+821012345678',\n postalCode: '06234',\n address1: '123 Main St',\n address2: 'Apt 4B',\n deliveryMessage?: 'Leave at door',\n },\n orderItems: [\n { product: 'product-id', variant: 'variant-id', option: 'option-id', quantity: 2, unitPrice: 29900 }\n ],\n totalAmount: 59800,\n shippingAmount?: 3000,\n pgPaymentId?: 'toss-payment-id', // omit for free orders\n})\n\\`\\`\\`\n\n### checkout()\nConvert a Cart to an Order.\n\n\\`\\`\\`typescript\nconst order = await client.commerce.orders.checkout({\n cartId: 'cart-id',\n orderNumber: 'ORD-20240101-0001',\n customerSnapshot: { name: 'John Doe', email: 'john@example.com' },\n pgPaymentId?: 'toss-payment-id',\n})\n\\`\\`\\`\n\n### getOrder()\nGet an order by order number.\n\n\\`\\`\\`typescript\nconst { docs } = await client.collections.from('orders').find({\n where: { orderNumber: { equals: 'ORD-20240101-0001' } },\n limit: 1,\n depth: 1,\n})\nconst order = docs[0] ?? null\n\\`\\`\\`\n\n### updateOrder()\nUpdate order status.\n\n\\`\\`\\`typescript\nconst order = await client.commerce.orders.update({\n orderNumber: 'ORD-20240101-0001',\n status: 'paid', // pending | paid | failed | canceled | preparing | shipped | delivered | confirmed\n})\n\\`\\`\\`\n\n## Fulfillment API\n\n### createFulfillment()\nCreate a shipment record for order items.\n\n\\`\\`\\`typescript\nconst fulfillment = await client.commerce.orders.createFulfillment({\n orderNumber: 'ORD-20240101-0001',\n carrier?: 'cj', // cj | hanjin | lotte | epost | logen | other\n trackingNumber?: '123456789012',\n items: [\n { orderItem: 'order-item-id', quantity: 2 }\n ],\n})\n\\`\\`\\`\n\n### updateFulfillment()\nUpdate fulfillment status and optionally carrier/tracking.\n\n\\`\\`\\`typescript\nconst fulfillment = await client.commerce.orders.updateFulfillment({\n fulfillmentId: 'fulfillment-id',\n status: 'delivered', // packed | shipped | delivered | failed\n carrier?: 'cj',\n trackingNumber?: '123456789012',\n})\n\\`\\`\\`\n\n## Return API\n\n### createReturn()\nCreate a return request (refund handled separately).\n\n\\`\\`\\`typescript\nconst ret = await client.commerce.orders.createReturn({\n orderNumber: 'ORD-20240101-0001',\n reason?: 'defective', // change_of_mind | defective | wrong_delivery | damaged | other\n reasonDetail?: 'Screen cracked on arrival',\n returnItems: [\n { orderItem: 'order-item-id', quantity: 1 }\n ],\n refundAmount: 29900,\n})\n\\`\\`\\`\n\n### updateReturn()\nUpdate return status.\n\n\\`\\`\\`typescript\nconst ret = await client.commerce.orders.updateReturn({\n returnId: 'return-id',\n status: 'processing', // processing | approved | completed | rejected\n})\n\\`\\`\\`\n\n### returnWithRefund()\nCreate a return and process a provider-verified refund in one atomic operation.\n\n\\`\\`\\`typescript\nconst result = await client.commerce.orders.returnWithRefund({\n orderNumber: 'ORD-20240101-0001',\n reason?: 'defective',\n reasonDetail?: 'Screen cracked on arrival',\n returnItems: [\n { orderItem: 'order-item-id', quantity: 1 }\n ],\n refundAmount: 29900,\n pgPaymentId: 'toss-payment-id', // required\n paymentKey: 'toss-payment-key', // required for provider refund\n refundReceiptUrl?: 'https://...',\n})\n\\`\\`\\`\n\n## Transaction API\n\n### updateTransaction()\nConfirm or annotate a transaction. Paid transitions require provider\nverification; non-financial annotations can still update pending transactions.\n\n\\`\\`\\`typescript\nconst tx = await client.commerce.orders.updateTransaction({\n pgPaymentId: 'toss-payment-id',\n status: 'paid', // pending | paid | failed | canceled\n paymentKey: 'toss-payment-key', // required when status is paid\n amount: 29900, // required when status is paid\n})\n\\`\\`\\`\n\n## Cart API\n\nCart operations use the \\`client.commerce.cart\\` namespace.\n\n### addItem()\nAdd an item to a cart.\n\n\\`\\`\\`typescript\nconst cart = await client.commerce.cart.addItem({\n cartId: 'cart-id',\n product: 'product-id',\n variant?: 'variant-id',\n option: 'option-id',\n quantity: 1,\n})\n\\`\\`\\`\n\n### updateItem()\nUpdate quantity of a cart item.\n\n\\`\\`\\`typescript\nconst cart = await client.commerce.cart.updateItem({\n cartItemId: 'cart-item-id',\n quantity: 3,\n})\n\\`\\`\\`\n\n### removeItem()\nRemove a single item from a cart.\n\n\\`\\`\\`typescript\nconst cart = await client.commerce.cart.removeItem({ cartItemId: 'cart-item-id' })\n\\`\\`\\`\n\n### clear()\nRemove all items from a cart (resets discount and amounts; preserves shippingAmount).\n\n\\`\\`\\`typescript\nconst cart = await client.commerce.cart.clear({ cartId: 'cart-id' })\n\\`\\`\\`\n\n### applyDiscount()\nApply a discount code to a cart.\n\n\\`\\`\\`typescript\nconst cart = await client.commerce.cart.applyDiscount({\n cartId: 'cart-id',\n discountCode: 'SAVE10',\n})\n\\`\\`\\`\n\n### removeDiscount()\nRemove the current discount code from a cart.\n\n\\`\\`\\`typescript\nconst cart = await client.commerce.cart.removeDiscount({ cartId: 'cart-id' })\n\\`\\`\\`\n\n## Validation API\n\n### validateDiscount()\nValidate a discount code before applying it.\n\n\\`\\`\\`typescript\nconst result = await client.commerce.discounts.validate({\n code: 'SAVE10',\n orderAmount: 50000,\n customerId?: 'customer-id',\n})\n// result.discountAmount - calculated discount\n// result.freeShipping - true if free_shipping type\n\\`\\`\\`\n\n### calculateShipping()\nCalculate shipping fee based on policy and order amount.\n\n\\`\\`\\`typescript\nconst result = await client.commerce.shipping.calculate({\n shippingPolicyId?: 'policy-id', // uses default policy if omitted\n orderAmount: 50000,\n postalCode?: '63001', // for Jeju surcharge detection\n})\n// result.shippingAmount - calculated fee (0 if free shipping threshold met)\n// result.baseShippingAmount - base fee before surcharge\n// result.extraShippingAmount - Jeju surcharge (0 if not applicable)\n\\`\\`\\``\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-customer-auth',\n title: 'Customer Auth API',\n description: '01.software SDK Customer Auth API reference (client.customer)',\n}\n\nexport default function handler() {\n return `# Customer Auth API\n\nCustomer authentication and profile management is available via \\`client.customer\\` on the browser-side \\`Client\\`.\n\n\\`\\`\\`typescript\nimport { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n})\n\\`\\`\\`\n\n> \\`client.customer\\` is available on \\`Client\\` (createClient) only. \\`ServerClient\\` does not include it.\n\n## Authentication\n\n### register()\nRegister a new customer account.\n\n\\`\\`\\`typescript\nconst result = await client.customer.register({\n name: 'John Doe',\n email: 'john@example.com',\n password: 'password123',\n phone?: '+821012345678',\n})\n// result.customer - created customer object\n\\`\\`\\`\n\nRegistration creates a local customer account. Projects that need additional email verification should enforce it in application code.\n\n### login()\nAuthenticate with email and password.\n\n\\`\\`\\`typescript\nconst result = await client.customer.login({\n email: 'john@example.com',\n password: 'password123',\n})\n// result.token - JWT token (stored automatically)\n// result.customer - authenticated customer object\n\\`\\`\\`\n\n### refreshToken()\nRefresh the current JWT token.\n\n\\`\\`\\`typescript\nconst result = await client.customer.refreshToken()\n// result.token - new JWT token\n\\`\\`\\`\n\n### logout()\nClear the stored JWT token.\n\n\\`\\`\\`typescript\nclient.customer.logout()\n\\`\\`\\`\n\n## Profile\n\n### me()\nGet the currently authenticated customer's profile.\n\n\\`\\`\\`typescript\nconst customer = await client.customer.me()\n// Returns Customer object: id, name, email, phone, isVerified, marketingConsent, ...\n\\`\\`\\`\n\n### updateProfile()\nUpdate profile fields. Only \\`name\\`, \\`phone\\`, and \\`marketingConsent\\` are allowed.\n\n\\`\\`\\`typescript\nconst updated = await client.customer.updateProfile({\n name?: 'New Name',\n phone?: '+821098765432',\n marketingConsent?: true,\n})\n// Returns updated Customer object\n\\`\\`\\`\n\n## Password\n\n### forgotPassword()\nRequest a password reset. Sends the reset token to configured tenant webhooks; your webhook handler owns delivery.\n\n\\`\\`\\`typescript\nawait client.customer.forgotPassword('john@example.com')\n// Rate limited: 5 requests/min per tenant+email\n// Webhook receives: { resetPasswordToken, resetPasswordExpiresAt }\n\\`\\`\\`\n\n### resetPassword()\nReset password using the token received via webhook.\n\n\\`\\`\\`typescript\nawait client.customer.resetPassword(token, 'newPassword123')\n\\`\\`\\`\n\n### changePassword()\nChange password while authenticated (requires current password).\n\n\\`\\`\\`typescript\nawait client.customer.changePassword('currentPassword', 'newPassword123')\n\\`\\`\\`\n\n## Orders\n\n### listMine()\nGet the authenticated customer's order history.\n\n\\`\\`\\`typescript\nconst orders = await client.commerce.orders.listMine({\n page: 1,\n limit: 10,\n status: 'paid', // filter by order status\n})\n// orders.docs, orders.totalDocs, orders.hasNextPage, ...\n\\`\\`\\`\n\n## Token Management\n\n\\`\\`\\`typescript\n// Get the current JWT token\nconst token = client.customer.getToken()\n\n// Set a JWT token manually (e.g., from server-side auth)\nclient.customer.setToken('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...')\n\n// Check if a customer is currently authenticated\nconst isLoggedIn = client.customer.isAuthenticated() // boolean\n\n// Clear token (same as logout)\nclient.customer.logout()\n\\`\\`\\`\n\n## Full Auth Flow Example\n\n\\`\\`\\`typescript\n'use client'\n\nimport { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n})\n\n// Registration\nasync function handleRegister(email: string, password: string, name: string) {\n const result = await client.customer.register({ email, password, name })\n\n // Customer is created as a local account.\n return { status: 'success', customer: result.customer }\n}\n\n// Login\nasync function handleLogin(email: string, password: string) {\n const { token, customer } = await client.customer.login({ email, password })\n // token is automatically stored by the SDK\n return customer\n}\n\n// Protected request\nasync function loadProfile() {\n if (!client.customer.isAuthenticated()) {\n throw new Error('Not logged in')\n }\n return await client.customer.me()\n}\n\\`\\`\\``\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-browser-vs-server',\n title: 'Client vs ServerClient',\n description: 'When to use Client (createClient) vs ServerClient (createServerClient) in the 01.software SDK',\n}\n\nexport default function handler() {\n return `# Client vs ServerClient\n\nThe SDK provides two client types for different execution environments.\n\n## Overview\n\n| Feature | Client | ServerClient |\n|---------|--------|-------------|\n| Import | \\`createClient\\` | \\`createServerClient\\` |\n| Environment | Browser / Client components | Server only |\n| Auth | \\`publishableKey\\` only | \\`publishableKey\\` + \\`secretKey\\` |\n| Read (\\`find\\`, \\`findById\\`, \\`count\\`) | Yes | Yes |\n| Write (\\`create\\`, \\`update\\`, \\`remove\\`) | No | Yes |\n| Bulk (\\`updateMany\\`, \\`removeMany\\`) | No | Yes |\n| React Query hooks (\\`client.query\\`) | Yes | Yes (SSR prefetch) |\n| Customer auth (\\`client.customer\\`) | Yes | No |\n| Server API (\\`client.api\\`) | No | Yes |\n\n## Client (createClient)\n\nUse in browser code, React client components, and anywhere the secret key must not be exposed.\n\n\\`\\`\\`typescript\nimport { createClient } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n})\n\n// Read data\nconst products = await client.collections.from('products').find({ limit: 10 })\n\n// React Query hooks\nconst { data } = client.query.useQuery({ collection: 'products' })\n\n// Customer auth\nawait client.customer.login({ email, password })\n\\`\\`\\`\n\n**Environment variable**: \\`NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY\\` (prefixed, exposed to browser)\n\n## ServerClient (createServerClient)\n\nUse in server components, API routes, server actions, and background jobs. Has full CRUD access.\n\n\\`\\`\\`typescript\nimport { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// Full CRUD\nconst product = await client.collections.from('products').create({\n title: 'New',\n status: 'draft',\n})\nawait client.collections.from('products').update('product-id', { title: 'Renamed Product' })\nawait client.collections.from('product-variants').create({\n product: product.doc.id,\n title: 'Default',\n price: 29900,\n stock: 10,\n})\nawait client.collections.from('products').remove('product-id')\n\n// Server API (orders, carts, etc.)\nawait client.commerce.orders.create({ ... })\nawait client.commerce.orders.checkout({ ... })\n\\`\\`\\`\n\n**Environment variables**:\n- \\`SOFTWARE_PUBLISHABLE_KEY\\` — publishable key (no NEXT_PUBLIC prefix, server-only)\n- \\`SOFTWARE_SECRET_KEY\\` — server credential\n\nNever expose \\`SOFTWARE_SECRET_KEY\\` in browser code, client bundles, logs, or\npublic repositories. If a secret key leaks, rotate it from the Console before\ndeploying again.\n\n## Decision Matrix\n\n| Scenario | Use |\n|----------|-----|\n| React component fetching public data | Client |\n| Infinite scroll / paginated list | Client |\n| Customer login / registration | Client |\n| Customer profile update | Client |\n| Next.js Server Component (read) | ServerClient |\n| Next.js API Route (mutation) | ServerClient |\n| Server Action (form submit) | ServerClient |\n| Order creation after payment | ServerClient |\n| Fulfillment / return processing | ServerClient |\n| SSR prefetch for React Query | ServerClient |\n| Webhook handler | ServerClient |\n| Background job / cron | ServerClient |\n\n## Next.js App Router Pattern\n\n\\`\\`\\`typescript\n// lib/sdk.ts — server-only module\nimport { createServerClient } from '@01.software/sdk'\n\nexport function getServerClient() {\n return createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n })\n}\n\\`\\`\\`\n\n\\`\\`\\`typescript\n// lib/sdk-client.ts — browser-safe module\nimport { createClient } from '@01.software/sdk'\n\nexport const browserClient = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n})\n\\`\\`\\`\n\n\\`\\`\\`typescript\n// app/products/page.tsx — Server Component\nimport { getServerClient } from '@/lib/sdk'\n\nexport default async function ProductsPage() {\n const client = getServerClient()\n const products = await client.collections.from('products').find({ limit: 20 })\n return <ProductList initialData={products} />\n}\n\\`\\`\\`\n\n\\`\\`\\`typescript\n// components/product-list.tsx — Client Component\n'use client'\nimport { browserClient } from '@/lib/sdk-client'\n\nexport function ProductList() {\n const { data } = browserClient.query.useQuery({ collection: 'products' })\n return <ul>{data?.docs.map(p => <li key={p.id}>{p.title}</li>)}</ul>\n}\n\\`\\`\\`\n\n## Security Rules\n\n- Keep server credentials in server-only modules.\n- Only \\`NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY\\` is safe to use in client components.\n- Never import a module that reads \\`SOFTWARE_SECRET_KEY\\` from a client component.\n- Rotate any exposed secret key immediately from the Console.\n\n> Ecommerce note: product card pricing lives on \\`products.listing.*\\`, but authoritative sellable pricing still lives on \\`product-variants.price\\`.`\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-file-upload',\n title: 'File Upload',\n description: '01.software SDK file upload patterns using the images collection',\n}\n\nexport default function handler() {\n return `# File Upload\n\nUpload files using the \\`images\\` collection (tenant-scoped, unified image store) or \\`system-media\\` (global, non-tenant).\n\n## Upload via images Collection\n\nUse \\`ServerClient\\` with \\`FormData\\` to upload images server-side.\n\n\\`\\`\\`typescript\nimport { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\n// Server-side upload (API Route or Server Action)\nasync function uploadImage(file: File) {\n const formData = new FormData()\n formData.append('file', file)\n formData.append('alt', 'Product image')\n\n const result = await client.collections.from('images').create(formData)\n return result.doc // { id, url, alt, width, height, ... }\n}\n\\`\\`\\`\n\n## Next.js API Route Example\n\n\\`\\`\\`typescript\n// app/api/upload/route.ts\nimport { NextRequest, NextResponse } from 'next/server'\nimport { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\nexport async function POST(req: NextRequest) {\n const formData = await req.formData()\n const file = formData.get('file') as File\n\n if (!file) {\n return NextResponse.json({ error: 'No file provided' }, { status: 400 })\n }\n\n const uploadForm = new FormData()\n uploadForm.append('file', file)\n uploadForm.append('alt', file.name)\n\n const result = await client.collections.from('images').create(uploadForm)\n return NextResponse.json({ url: result.doc.url, id: result.doc.id })\n}\n\\`\\`\\`\n\n## Server Action Example\n\n\\`\\`\\`typescript\n// actions/upload.ts\n'use server'\n\nimport { createServerClient } from '@01.software/sdk'\n\nconst client = createServerClient({\n publishableKey: process.env.SOFTWARE_PUBLISHABLE_KEY!,\n secretKey: process.env.SOFTWARE_SECRET_KEY!,\n})\n\nexport async function uploadProductImage(formData: FormData) {\n const file = formData.get('image') as File\n\n const uploadForm = new FormData()\n uploadForm.append('file', file)\n uploadForm.append('alt', formData.get('alt') as string || file.name)\n\n const result = await client.collections.from('images').create(uploadForm)\n return { id: result.doc.id, url: result.doc.url }\n}\n\\`\\`\\`\n\n## Client Component with Upload Form\n\n\\`\\`\\`typescript\n'use client'\n\nexport function ImageUploadForm() {\n async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {\n e.preventDefault()\n const formData = new FormData(e.currentTarget)\n const { id, url } = await uploadProductImage(formData)\n console.log('Uploaded:', url)\n }\n\n return (\n <form onSubmit={handleSubmit}>\n <input type=\"file\" name=\"image\" accept=\"image/*\" required />\n <input type=\"text\" name=\"alt\" placeholder=\"Alt text\" />\n <button type=\"submit\">Upload</button>\n </form>\n )\n}\n\\`\\`\\`\n\n## Image Collections\n\n| Collection | Purpose | Scope |\n|------------|---------|-------|\n| \\`images\\` | All tenant image assets | Tenant-scoped |\n| \\`system-media\\` | Platform-level assets | Global (non-tenant) |\n| \\`brand-logos\\` | Brand logo uploads | Tenant-scoped |\n| \\`tenant-logos\\` | Tenant logo uploads | Per-tenant |\n\n## Linking Uploaded Images to Documents\n\nAfter uploading, use the returned \\`id\\` to link the image to other collections.\n\n\\`\\`\\`typescript\n// 1. Upload image\nconst { id: imageId, url } = await uploadImage(file)\n\n// 2. Create product with image reference\nconst product = await client.collections.from('products').create({\n title: 'Product with Image',\n thumbnail: imageId, // relationship to images collection\n status: 'draft',\n})\n\\`\\`\\`\n\n## Supported Formats\n\nThe platform stores files in Cloudflare R2 and serves via CDN (\\`cdn.01.software\\`). Common image formats are supported: JPEG, PNG, WebP, GIF, SVG.\n\n## Storage Quotas by Plan\n\n| Plan | Storage |\n|------|---------|\n| Free | 10 GB |\n| Starter | 100 GB |\n| Basic | 300 GB |\n| Pro | 1 TB |\n| Enterprise | Unlimited |`\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-webhook',\n title: 'Webhooks',\n description: '01.software SDK webhook verification and event handling',\n}\n\nexport default function handler() {\n return `# Webhooks\n\nThe platform dispatches HMAC-SHA256 signed webhook events to your registered URLs. Tenant developers own routing inside their webhook handler.\n\n## Webhook Handling\n\nUse the SDK \\`handleWebhook\\` helper to verify signatures. For customer auth events, use \\`createCustomerAuthWebhookHandler\\` to wire delivery behavior in your app.\n\n\\`\\`\\`typescript\nimport { handleWebhook, createCustomerAuthWebhookHandler } from '@01.software/sdk/webhook'\n\nconst handler = createCustomerAuthWebhookHandler({\n passwordReset: async (data) => {\n await sendPasswordResetEmail(data)\n },\n})\n\nexport async function POST(request: Request) {\n return handleWebhook(request, handler, {\n secret: process.env.WEBHOOK_SECRET!,\n })\n}\n\\`\\`\\`\n\n**Environment variable**: \\`WEBHOOK_SECRET\\` — the shared HMAC secret set in your tenant webhook configuration.\n\n## Next.js API Route Example\n\n\\`\\`\\`typescript\n// app/api/webhooks/route.ts\nimport { handleWebhook, createCustomerAuthWebhookHandler } from '@01.software/sdk/webhook'\n\nconst customerAuthHandler = createCustomerAuthWebhookHandler({\n passwordReset: sendPasswordResetEmail,\n})\n\nexport async function POST(request: Request) {\n return handleWebhook(request, async (event) => {\n console.log('Webhook received:', event.collection, event.operation)\n\n await customerAuthHandler(event)\n }, {\n secret: process.env.WEBHOOK_SECRET!,\n })\n}\n\\`\\`\\`\n\n## Webhook Payload Structure\n\nAll webhook events share this envelope:\n\n\\`\\`\\`typescript\n{\n collection: string, // e.g. 'customers'\n operation: string, // e.g. 'password-reset'\n data: object, // event-specific payload\n}\n\\`\\`\\`\n\n## Event Types\n\n### Customer Password Reset\n\nDispatched when a customer calls \\`client.customer.forgotPassword(email)\\`.\n\n\\`\\`\\`typescript\n{\n collection: 'customers',\n operation: 'password-reset',\n data: {\n customerId: string,\n email: string,\n name: string,\n resetPasswordToken: string, // raw token to include in reset link\n resetPasswordExpiresAt: string, // ISO 8601 expiry (1 hour from dispatch)\n }\n}\n\\`\\`\\`\n\n**Usage**: Send the \\`resetPasswordToken\\` to the customer. They call \\`client.customer.resetPassword(token, newPassword)\\`.\n\n\\`\\`\\`typescript\nasync function sendPasswordResetEmail(data: {\n customerId: string\n email: string\n name: string\n resetPasswordToken: string\n resetPasswordExpiresAt: string\n}) {\n const resetUrl = \\`https://yourstore.com/reset-password?token=\\${data.resetPasswordToken}\\`\n await emailService.send({\n to: data.email,\n subject: 'Reset your password',\n body: \\`Reset link (expires \\${data.resetPasswordExpiresAt}): \\${resetUrl}\\`,\n })\n}\n\\`\\`\\`\n\n## Webhook Retry\n\nFailed webhook deliveries are queued with automatic retries. Ensure your handler returns a 2xx response promptly. Long-running operations should be offloaded to a background job.\n\n## Webhook Configuration\n\nConfigure webhook URLs in the 01.software console under Tenant Settings > Webhooks. Multiple URLs can be registered; all receive every event.`\n}\n","import { type ResourceMetadata } from '../../types'\n\nexport const metadata: ResourceMetadata = {\n name: 'docs-product-detail',\n title: 'Product Detail Helper',\n description: '01.software SDK commerce.product.detail helper guide',\n}\n\nexport default function handler() {\n return `# Product Detail Helper\n\n## When to use the helper vs the raw query builder\n\nUse \\`client.commerce.product.detail({ slug | id })\\` when you need a full product detail page payload in one call. The helper folds the Payload query, access policy, and response shaping (variants, options, option value slugs/media, brand, categories, tags, images, videos, listing rollup) into a single call.\n\nUse \\`client.collections.from('products').find(...)\\` (escape hatch) when you need bulk reads, custom filter combinations, or fields outside the helper response shape.\n\n## Single-call example\n\n\\`\\`\\`typescript\nimport { createClient, resolveProductSelection } from '@01.software/sdk'\n\nconst client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n})\n\nconst detail = await client.commerce.product.detail({ slug: 'my-product' })\nif (!detail) return notFound()\nconst selection = resolveProductSelection(detail, {\n search: '?opt.color=black&opt.size=large',\n})\n// selection.selectedVariant, selection.price, selection.stock, selection.media\n\\`\\`\\`\n\n## URL round-trip\n\nUse the SDK codec for one canonical selection URL format: \\`opt.<optionSlug>=<valueSlug>\\`. Option and value slugs are the stable public tokens exposed by product detail.\n\n\\`\\`\\`typescript\nimport { createProductSelectionCodec } from '@01.software/sdk'\n\nconst codec = createProductSelectionCodec(detail)\nconst selection = codec.parse('?opt.color=black')\nconst href = codec.stringify(selection)\n\\`\\`\\`\n\nValue-slug-only URLs such as \\`?black\\` or \\`?color=black\\` are rejected because option titles are not stable identifiers.\n\n## React Query hook variant\n\n\\`\\`\\`typescript\nconst { data: detail, isLoading } = client.query.useProductDetailBySlug(slug)\n\\`\\`\\`\n\nCache invalidates automatically when any of 10 detail-relevant collections is mutated through SDK mutation hooks.\n\n## SSG / Server Component snippet\n\n\\`\\`\\`tsx\n// app/products/[slug]/page.tsx\nimport { createClient } from '@01.software/sdk'\nimport { notFound } from 'next/navigation'\n\nexport const revalidate = 60\n\nexport default async function ProductPage({ params }: { params: { slug: string } }) {\n const client = createClient({\n publishableKey: process.env.NEXT_PUBLIC_SOFTWARE_PUBLISHABLE_KEY!,\n })\n const detail = await client.commerce.product.detail({ slug: params.slug })\n if (!detail) return notFound()\n return <ProductView detail={detail} />\n}\n\\`\\`\\`\n\n## The \\`null\\` return contract\n\nThe endpoint returns 404 for \\`not_found\\`, \\`not_published\\`, \\`tenant_mismatch\\`, or \\`feature_disabled\\`. The SDK collapses all 404s to \\`null\\` so consumer UIs render one \"not available\" path.\n\n## Backend correlation\n\nLog \\`client.lastRequestId\\` against backend logs — the endpoint records the exact 404 code alongside the request ID.`\n}\n"],"mappings":";AAAA,SAAS,iBAAiB;;;ACA1B,SAAS,yBAAyB;AAQ3B,IAAM,iBAAiB,IAAI,kBAAkC;AAiB7D,SAAS,oBAA8C;AAC5D,SAAO,eAAe,SAAS,GAAG,QAAQ;AAC5C;AAEO,SAAS,oBAA6B;AAC3C,SAAO,eAAe,SAAS,MAAM;AACvC;;;ACxBO,SAAS,YAAY,MAAuC;AACjE,SAAO,KAAK,UAAU,EAAE,SAAS,MAAM,GAAG,KAAK,GAAG,MAAM,CAAC;AAC3D;AAWO,SAAS,UAAU,OAAwB;AAChD,QAAM,OAAgC,EAAE,SAAS,MAAM;AACvD,QAAM,eACJ,CAAC,CAAC,SAAS,OAAO,UAAU,aAAa,UAAU,SAAS,YAAY;AAE1E,MAAI,cAAc;AAChB,UAAM,SAAS;AASf,SAAK,QAAQ,OAAO,WAAW;AAC/B,QAAI,OAAO,OAAQ,MAAK,SA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AE;AAAA,IACAD;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACAD;AAAA,IACAE;AAAA,IACAD;AAAA,EACF;AAIA;AAAA,IACE;AAAA,IACAD;AAAA,IACAE;AAAA,IACA;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACAF;AAAA,IACAE;AAAA,IACA;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACAF;AAAA,IACAE;AAAA,IACA;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACAF;AAAA,IACAE;AAAA,IACA;AAAA,EACF;AAIA;AAAA,IACE;AAAA,IACA;AAAA,IACAA;AAAA,IACAD;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACAC;AAAA,IACAD;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACAC;AAAA,IACAD;AAAA,EACF;AACA,yBAAuB,QAAQ,qBAAqBC,YAAYD,SAAa;AAC7E,yBAAuB,QAAQ,kBAAkBC,YAASD,SAAU;AACpE;AAAA,IACE;AAAA,IACA;AAAA,IACAC;AAAA,IACAD;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACAC;AAAA,IACAD;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACAC;AAAA,IACAD;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACAC;AAAA,IACAD;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACAC;AAAA,IACAD;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACAC;AAAA,IACAD;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACAC;AAAA,IACAD;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACA;AAAA,IACAC;AAAA,IACAD;AAAA,EACF;AAEA,SAAO;AACT;","names":["z","z","AsyncLocalStorage","randomUUID","AsyncLocalStorage","randomUUID","z","MISSING_HTTP_AUTH_CONTEXT_ERROR","z","z","SERVER_COLLECTIONS","schema","z","SERVER_COLLECTIONS","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","schema","metadata","z","schema","z","metadata","z","schema","z","metadata","schema","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","z","z","schema","metadata","SERVER_COLLECTIONS","schema","SERVER_COLLECTIONS","metadata","schema","metadata","schema","metadata","handler","z","schema","z","metadata","z","schema","z","metadata","z","schema","z","metadata","handler","z","schema","z","metadata","handler","z","schema","z","metadata","handler","z","SERVER_COLLECTIONS","schema","z","SERVER_COLLECTIONS","metadata","parts","handler","z","schema","metadata","z","COLLECTIONS","SERVER_COLLECTIONS","schema","metadata","z","schema","metadata","z","schema","metadata","metadata","handler","COLLECTIONS","metadata","handler","COLLECTIONS","metadata","handler","metadata","handler","metadata","handler","metadata","handler","metadata","handler","metadata","handler","metadata","handler","metadata","handler","metadata","handler","metadata","handler","metadata","handler","schema","handler","metadata"]}
|