@hashgraphonline/conversational-agent 0.1.215 → 0.1.217
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/cjs/conversational-agent.d.ts +8 -0
- package/dist/cjs/core/ToolRegistry.d.ts +130 -0
- package/dist/cjs/execution/ExecutionPipeline.d.ts +81 -0
- package/dist/cjs/forms/FormEngine.d.ts +121 -0
- package/dist/cjs/forms/form-generator.d.ts +39 -2
- package/dist/cjs/forms/types.d.ts +21 -2
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.ts +3 -4
- package/dist/cjs/langchain/FormAwareAgentExecutor.d.ts +53 -4
- package/dist/cjs/langchain/FormValidatingToolWrapper.d.ts +43 -6
- package/dist/cjs/langchain-agent.d.ts +49 -0
- package/dist/cjs/memory/ContentStorage.d.ts +7 -0
- package/dist/cjs/memory/SmartMemoryManager.d.ts +1 -0
- package/dist/cjs/services/ContentStoreManager.d.ts +11 -1
- package/dist/cjs/utils/ResponseFormatter.d.ts +26 -0
- package/dist/esm/index.js +2 -6
- package/dist/esm/index12.js +1 -1
- package/dist/esm/index12.js.map +1 -1
- package/dist/esm/index14.js +23 -5
- package/dist/esm/index14.js.map +1 -1
- package/dist/esm/index15.js +25 -4
- package/dist/esm/index15.js.map +1 -1
- package/dist/esm/index16.js +4 -2
- package/dist/esm/index16.js.map +1 -1
- package/dist/esm/index17.js +2 -7
- package/dist/esm/index17.js.map +1 -1
- package/dist/esm/index18.js +292 -150
- package/dist/esm/index18.js.map +1 -1
- package/dist/esm/index19.js +158 -65
- package/dist/esm/index19.js.map +1 -1
- package/dist/esm/index20.js +94 -270
- package/dist/esm/index20.js.map +1 -1
- package/dist/esm/index21.js +1 -1
- package/dist/esm/index23.js +14 -0
- package/dist/esm/index23.js.map +1 -1
- package/dist/esm/index24.js +508 -12
- package/dist/esm/index24.js.map +1 -1
- package/dist/esm/index25.js +1 -1
- package/dist/esm/index25.js.map +1 -1
- package/dist/esm/index26.js +1 -1
- package/dist/esm/index26.js.map +1 -1
- package/dist/esm/index27.js +189 -128
- package/dist/esm/index27.js.map +1 -1
- package/dist/esm/index28.js +164 -45
- package/dist/esm/index28.js.map +1 -1
- package/dist/esm/index29.js +302 -24
- package/dist/esm/index29.js.map +1 -1
- package/dist/esm/index30.js +144 -80
- package/dist/esm/index30.js.map +1 -1
- package/dist/esm/index31.js +63 -7
- package/dist/esm/index31.js.map +1 -1
- package/dist/esm/index32.js +24 -236
- package/dist/esm/index32.js.map +1 -1
- package/dist/esm/index33.js +95 -0
- package/dist/esm/index33.js.map +1 -0
- package/dist/esm/index34.js +245 -0
- package/dist/esm/index34.js.map +1 -0
- package/dist/esm/index5.js.map +1 -1
- package/dist/esm/index6.js +61 -22
- package/dist/esm/index6.js.map +1 -1
- package/dist/esm/index8.js +653 -131
- package/dist/esm/index8.js.map +1 -1
- package/dist/types/conversational-agent.d.ts +8 -0
- package/dist/types/core/ToolRegistry.d.ts +130 -0
- package/dist/types/execution/ExecutionPipeline.d.ts +81 -0
- package/dist/types/forms/FormEngine.d.ts +121 -0
- package/dist/types/forms/form-generator.d.ts +39 -2
- package/dist/types/forms/types.d.ts +21 -2
- package/dist/types/index.d.ts +3 -4
- package/dist/types/langchain/FormAwareAgentExecutor.d.ts +53 -4
- package/dist/types/langchain/FormValidatingToolWrapper.d.ts +43 -6
- package/dist/types/langchain-agent.d.ts +49 -0
- package/dist/types/memory/ContentStorage.d.ts +7 -0
- package/dist/types/memory/SmartMemoryManager.d.ts +1 -0
- package/dist/types/services/ContentStoreManager.d.ts +11 -1
- package/dist/types/utils/ResponseFormatter.d.ts +26 -0
- package/package.json +13 -10
- package/src/config/system-message.ts +14 -0
- package/src/context/ReferenceContextManager.ts +1 -1
- package/src/conversational-agent.ts +91 -36
- package/src/core/ToolRegistry.ts +358 -0
- package/src/execution/ExecutionPipeline.ts +301 -0
- package/src/forms/FormEngine.ts +443 -0
- package/src/forms/field-type-registry.ts +1 -13
- package/src/forms/form-generator.ts +394 -237
- package/src/forms/types.ts +20 -3
- package/src/index.ts +6 -10
- package/src/langchain/FormAwareAgentExecutor.ts +653 -22
- package/src/langchain/FormValidatingToolWrapper.ts +216 -93
- package/src/langchain-agent.ts +924 -185
- package/src/mcp/ContentProcessor.ts +20 -4
- package/src/mcp/MCPClientManager.ts +1 -1
- package/src/mcp/adapters/langchain.ts +1 -1
- package/src/memory/ContentStorage.ts +25 -5
- package/src/memory/SmartMemoryManager.ts +27 -4
- package/src/memory/TokenCounter.ts +1 -1
- package/src/plugins/hbar/HbarPlugin.ts +0 -1
- package/src/scripts/test-external-tool-wrapper.ts +3 -12
- package/src/scripts/test-hedera-kit-wrapper.ts +6 -22
- package/src/scripts/test-inscribe-form-generation.ts +24 -42
- package/src/scripts/test-inscribe-wrapper-verification.ts +1 -7
- package/src/services/ContentStoreManager.ts +23 -9
- package/src/services/EntityResolver.ts +2 -9
- package/src/tools/EntityResolverTool.ts +5 -8
- package/src/utils/ResponseFormatter.ts +146 -0
- package/dist/cjs/examples/external-tool-wrapper-example.d.ts +0 -131
- package/dist/cjs/langchain/ContentAwareAgentExecutor.d.ts +0 -14
- package/dist/cjs/langchain/external-tool-wrapper.d.ts +0 -179
- package/dist/cjs/scripts/test-external-tool-wrapper.d.ts +0 -5
- package/dist/cjs/scripts/test-hedera-kit-wrapper.d.ts +0 -36
- package/dist/cjs/scripts/test-inscribe-form-generation.d.ts +0 -15
- package/dist/cjs/scripts/test-inscribe-wrapper-verification.d.ts +0 -13
- package/dist/types/examples/external-tool-wrapper-example.d.ts +0 -131
- package/dist/types/langchain/ContentAwareAgentExecutor.d.ts +0 -14
- package/dist/types/langchain/external-tool-wrapper.d.ts +0 -179
- package/dist/types/scripts/test-external-tool-wrapper.d.ts +0 -5
- package/dist/types/scripts/test-hedera-kit-wrapper.d.ts +0 -36
- package/dist/types/scripts/test-inscribe-form-generation.d.ts +0 -15
- package/dist/types/scripts/test-inscribe-wrapper-verification.d.ts +0 -13
- package/src/examples/external-tool-wrapper-example.ts +0 -227
- package/src/langchain/ContentAwareAgentExecutor.ts +0 -19
- package/src/langchain/external-tool-wrapper.ts +0 -486
package/dist/esm/index29.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index29.js","sources":["../../src/types/content-reference.ts"],"sourcesContent":["/**\n * Content Reference System Types\n * \n * Shared interfaces for the Reference-Based Content System that handles\n * large content storage with unique reference IDs to optimize context window usage.\n */\n\n/**\n * Unique identifier for stored content references\n * Format: Cryptographically secure 32-byte identifier with base64url encoding\n */\nexport type ReferenceId = string;\n\n/**\n * Lifecycle state of a content reference\n */\nexport type ReferenceLifecycleState = 'active' | 'expired' | 'cleanup_pending' | 'invalid';\n\n/**\n * Content types supported by the reference system\n */\nexport type ContentType = 'text' | 'json' | 'html' | 'markdown' | 'binary' | 'unknown';\n\n/**\n * Sources that created the content reference\n */\nexport type ContentSource = 'mcp_tool' | 'user_upload' | 'agent_generated' | 'system';\n\n/**\n * Metadata associated with stored content\n */\nexport interface ContentMetadata {\n /** Content type classification */\n contentType: ContentType;\n \n /** MIME type of the original content */\n mimeType?: string;\n \n /** Size in bytes of the stored content */\n sizeBytes: number;\n \n /** When the content was originally stored */\n createdAt: Date;\n \n /** Last time the content was accessed via reference resolution */\n lastAccessedAt: Date;\n \n /** Source that created this content reference */\n source: ContentSource;\n \n /** Name of the MCP tool that generated the content (if applicable) */\n mcpToolName?: string;\n \n /** Original filename or suggested name for the content */\n fileName?: string;\n \n /** Number of times this reference has been resolved */\n accessCount: number;\n \n /** Tags for categorization and cleanup policies */\n tags?: string[];\n \n /** Custom metadata from the source */\n customMetadata?: Record<string, unknown>;\n}\n\n/**\n * Core content reference object passed through agent context\n * Designed to be lightweight (<100 tokens) while providing enough \n * information for agent decision-making\n */\nexport interface ContentReference {\n /** Unique identifier for resolving the content */\n referenceId: ReferenceId;\n \n /** Current lifecycle state */\n state: ReferenceLifecycleState;\n \n /** Brief description or preview of the content (max 200 chars) */\n preview: string;\n \n /** Essential metadata for agent decision-making */\n metadata: Pick<ContentMetadata, 'contentType' | 'sizeBytes' | 'source' | 'fileName' | 'mimeType'>;\n \n /** When this reference was created */\n createdAt: Date;\n \n /** Special format indicator for reference IDs in content */\n readonly format: 'ref://{id}';\n}\n\n/**\n * Result of attempting to resolve a content reference\n */\nexport interface ReferenceResolutionResult {\n /** Whether the resolution was successful */\n success: boolean;\n \n /** The resolved content if successful */\n content?: Buffer;\n \n /** Complete metadata if successful */\n metadata?: ContentMetadata;\n \n /** Error message if resolution failed */\n error?: string;\n \n /** Specific error type for targeted error handling */\n errorType?: 'not_found' | 'expired' | 'corrupted' | 'access_denied' | 'system_error';\n \n /** Suggested actions for recovery */\n suggestedActions?: string[];\n}\n\n/**\n * Configuration for content reference storage and lifecycle\n */\nexport interface ContentReferenceConfig {\n /** Size threshold above which content should be stored as references (default: 10KB) */\n sizeThresholdBytes: number;\n \n /** Maximum age for unused references before cleanup (default: 1 hour) */\n maxAgeMs: number;\n \n /** Maximum number of references to store simultaneously */\n maxReferences: number;\n \n /** Maximum total storage size for all references */\n maxTotalStorageBytes: number;\n \n /** Whether to enable automatic cleanup */\n enableAutoCleanup: boolean;\n \n /** Interval for cleanup checks in milliseconds */\n cleanupIntervalMs: number;\n \n /** Whether to persist references across restarts */\n enablePersistence: boolean;\n \n /** Storage backend configuration */\n storageBackend: 'memory' | 'filesystem' | 'hybrid';\n \n /** Cleanup policies for different content types */\n cleanupPolicies: {\n /** Policy for content marked as \"recent\" from MCP tools */\n recent: { maxAgeMs: number; priority: number };\n \n /** Policy for user-uploaded content */\n userContent: { maxAgeMs: number; priority: number };\n \n /** Policy for agent-generated content */\n agentGenerated: { maxAgeMs: number; priority: number };\n \n /** Default policy for other content */\n default: { maxAgeMs: number; priority: number };\n };\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_CONTENT_REFERENCE_CONFIG: ContentReferenceConfig = {\n sizeThresholdBytes: 10 * 1024,\n maxAgeMs: 60 * 60 * 1000,\n maxReferences: 100,\n maxTotalStorageBytes: 100 * 1024 * 1024,\n enableAutoCleanup: true,\n cleanupIntervalMs: 5 * 60 * 1000,\n enablePersistence: false,\n storageBackend: 'memory',\n cleanupPolicies: {\n recent: { maxAgeMs: 30 * 60 * 1000, priority: 1 },\n userContent: { maxAgeMs: 2 * 60 * 60 * 1000, priority: 2 },\n agentGenerated: { maxAgeMs: 60 * 60 * 1000, priority: 3 },\n default: { maxAgeMs: 60 * 60 * 1000, priority: 4 }\n }\n};\n\n/**\n * Statistics about content reference usage and storage\n */\nexport interface ContentReferenceStats {\n /** Total number of active references */\n activeReferences: number;\n \n /** Total storage used by all references in bytes */\n totalStorageBytes: number;\n \n /** Number of references cleaned up in last cleanup cycle */\n recentlyCleanedUp: number;\n \n /** Number of successful reference resolutions since startup */\n totalResolutions: number;\n \n /** Number of failed resolution attempts */\n failedResolutions: number;\n \n /** Average content size in bytes */\n averageContentSize: number;\n \n /** Most frequently accessed reference ID */\n mostAccessedReferenceId?: ReferenceId;\n \n /** Storage utilization percentage */\n storageUtilization: number;\n \n /** Performance metrics */\n performanceMetrics: {\n /** Average time to create a reference in milliseconds */\n averageCreationTimeMs: number;\n \n /** Average time to resolve a reference in milliseconds */\n averageResolutionTimeMs: number;\n \n /** Average cleanup time in milliseconds */\n averageCleanupTimeMs: number;\n };\n}\n\n/**\n * Error types for content reference operations\n */\nexport class ContentReferenceError extends Error {\n constructor(\n message: string,\n public readonly type: ReferenceResolutionResult['errorType'],\n public readonly referenceId?: ReferenceId,\n public readonly suggestedActions?: string[]\n ) {\n super(message);\n this.name = 'ContentReferenceError';\n }\n}\n\n/**\n * Interface for content reference storage implementations\n */\nexport interface ContentReferenceStore {\n /**\n * Store content and return a reference\n */\n storeContent(\n content: Buffer,\n metadata: Omit<ContentMetadata, 'createdAt' | 'lastAccessedAt' | 'accessCount'>\n ): Promise<ContentReference>;\n \n /**\n * Resolve a reference to its content\n */\n resolveReference(referenceId: ReferenceId): Promise<ReferenceResolutionResult>;\n \n /**\n * Check if a reference exists and is valid\n */\n hasReference(referenceId: ReferenceId): Promise<boolean>;\n \n /**\n * Mark a reference for cleanup\n */\n cleanupReference(referenceId: ReferenceId): Promise<boolean>;\n \n /**\n * Get current storage statistics\n */\n getStats(): Promise<ContentReferenceStats>;\n \n /**\n * Update configuration\n */\n updateConfig(config: Partial<ContentReferenceConfig>): Promise<void>;\n \n /**\n * Perform cleanup based on current policies\n */\n performCleanup(): Promise<{ cleanedUp: number; errors: string[] }>;\n \n /**\n * Dispose of resources\n */\n dispose(): Promise<void>;\n}"],"names":[],"mappings":"AAiKO,MAAM,mCAA2D;AAAA,EACtE,oBAAoB,KAAK;AAAA,EACzB,UAAU,KAAK,KAAK;AAAA,EACpB,eAAe;AAAA,EACf,sBAAsB,MAAM,OAAO;AAAA,EACnC,mBAAmB;AAAA,EACnB,mBAAmB,IAAI,KAAK;AAAA,EAC5B,mBAAmB;AAAA,EACnB,gBAAgB;AAAA,EAChB,iBAAiB;AAAA,IACf,QAAQ,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IAC9C,aAAa,EAAE,UAAU,IAAI,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACvD,gBAAgB,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,IACtD,SAAS,EAAE,UAAU,KAAK,KAAK,KAAM,UAAU,EAAA;AAAA,EAAE;AAErD;AA8CO,MAAM,8BAA8B,MAAM;AAAA,EAC/C,YACE,SACgB,MACA,aACA,kBAChB;AACA,UAAM,OAAO;AAJG,SAAA,OAAA;AACA,SAAA,cAAA;AACA,SAAA,mBAAA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;"}
|
|
1
|
+
{"version":3,"file":"index29.js","sources":["../../src/forms/FormEngine.ts"],"sourcesContent":["import { StructuredTool } from '@langchain/core/tools';\nimport { ZodError, z } from 'zod';\nimport { Logger } from '@hashgraphonline/standards-sdk';\nimport { FormGenerator } from './form-generator';\nimport { isFormValidatable } from '@hashgraphonline/standards-agent-kit';\nimport type { FormMessage, FormSubmission } from './types';\n\n/**\n * Tool execution result with optional form requirement\n */\nexport interface ToolExecutionResult {\n success: boolean;\n output: string;\n metadata?: Record<string, unknown>;\n requiresForm?: boolean;\n formMessage?: FormMessage;\n error?: string;\n}\n\n/**\n * Context for form generation operations\n */\nexport interface FormGenerationContext {\n tool: StructuredTool;\n input: unknown;\n sessionId?: string;\n userId?: string;\n missingFields?: Set<string>;\n}\n\n/**\n * FormEngine handles all form generation and validation logic\n */\nexport class FormEngine {\n private formGenerator: FormGenerator;\n private logger: Logger;\n\n constructor(logger?: Logger) {\n this.formGenerator = new FormGenerator();\n this.logger = logger || new Logger({ module: 'FormEngine' });\n }\n\n /**\n * Generate a form for a tool with the given input\n */\n async generateForm(\n toolName: string,\n tool: StructuredTool,\n input: unknown,\n context?: Partial<FormGenerationContext>\n ): Promise<FormMessage | null> {\n const fullContext: FormGenerationContext = {\n tool,\n input,\n ...context\n };\n\n try {\n if (isFormValidatable(tool)) {\n return await this.generateFormValidatableForm(tool, input, fullContext);\n }\n\n if (input instanceof ZodError) {\n return await this.generateErrorBasedForm(tool, input, fullContext);\n }\n\n if (this.hasRenderConfig(tool)) {\n return await this.generateRenderConfigForm(tool, input, fullContext);\n }\n\n if (this.isZodObject(tool.schema)) {\n return await this.generateSchemaBasedForm(tool, input, fullContext);\n }\n\n return null;\n } catch (error) {\n this.logger.error(`Failed to generate form for tool: ${toolName}`, {\n error: error instanceof Error ? error.message : String(error)\n });\n throw error;\n }\n }\n\n /**\n * Process a form submission\n */\n async processSubmission(\n submission: FormSubmission,\n context?: {\n originalInput?: Record<string, unknown>;\n schema?: unknown;\n }\n ): Promise<Record<string, unknown>> {\n this.validateSubmission(submission);\n \n const baseToolInput = this.extractBaseToolInput(context);\n const submissionData = this.extractSubmissionData(submission);\n \n return this.mergeInputData(baseToolInput, submissionData);\n }\n\n /**\n * Check if a tool requires form generation based on input\n */\n shouldGenerateForm(tool: StructuredTool, input: unknown): boolean {\n const inputRecord = input as Record<string, unknown>;\n if (inputRecord?.__fromForm === true || inputRecord?.renderForm === false) {\n return false;\n }\n\n if (isFormValidatable(tool)) {\n try {\n const formValidatableTool = tool as {\n shouldGenerateForm: (input: unknown) => boolean;\n };\n return formValidatableTool.shouldGenerateForm(input);\n } catch (error) {\n this.logger.error(`Error calling shouldGenerateForm() on ${tool.name}:`, error);\n return false;\n }\n }\n\n const validation = this.validateInput(tool, input);\n return !validation.isValid;\n }\n\n /**\n * Generate form from error context\n */\n async generateFormFromError(\n error: ZodError,\n toolName: string,\n toolSchema: z.ZodSchema,\n originalPrompt: string\n ): Promise<FormMessage> {\n return this.formGenerator.generateFormFromError(\n error,\n toolSchema as z.ZodType<unknown, z.ZodTypeDef, unknown>,\n toolName,\n originalPrompt\n );\n }\n\n /**\n * Generate form for FormValidatable tools\n */\n private async generateFormValidatableForm(\n tool: StructuredTool,\n input: unknown,\n _context: FormGenerationContext\n ): Promise<FormMessage> {\n const { schemaToUse, isFocusedSchema } = this.resolveFormSchema(tool);\n const missingFields = this.determineMissingFields(tool, input, schemaToUse, isFocusedSchema);\n \n return this.generateFormWithSchema(tool, input, schemaToUse, missingFields);\n }\n\n /**\n * Generate form based on schema validation\n */\n private async generateSchemaBasedForm(\n tool: StructuredTool,\n input: unknown,\n context: FormGenerationContext\n ): Promise<FormMessage> {\n const schema = tool.schema;\n\n const formMessage = await this.formGenerator.generateFormFromSchema(\n schema as z.ZodType<unknown, z.ZodTypeDef, unknown>,\n input,\n {\n toolName: tool.name,\n toolDescription: tool.description\n },\n context.missingFields\n );\n\n if (this.isZodObject(schema)) {\n try {\n const { jsonSchema, uiSchema } = this.formGenerator.generateJsonSchemaForm(\n schema,\n input as Record<string, unknown> | undefined,\n context.missingFields || new Set()\n );\n formMessage.jsonSchema = jsonSchema;\n formMessage.uiSchema = uiSchema;\n } catch (error) {\n this.logger.warn('Failed to generate JSON Schema for schema-based tool:', error);\n }\n }\n\n formMessage.partialInput = input;\n return formMessage;\n }\n\n /**\n * Generate form based on render config\n */\n private async generateRenderConfigForm(\n tool: StructuredTool,\n input: unknown,\n context: FormGenerationContext\n ): Promise<FormMessage> {\n const schema = tool.schema;\n const renderConfig = this.extractRenderConfig(tool);\n\n const formMessage = await this.formGenerator.generateFormFromSchema(\n schema as z.ZodType<unknown, z.ZodTypeDef, unknown>,\n input,\n {\n toolName: tool.name,\n toolDescription: tool.description\n },\n context.missingFields\n );\n\n if (renderConfig) {\n formMessage.formConfig.metadata = {\n ...formMessage.formConfig.metadata,\n renderConfig\n };\n }\n \n formMessage.partialInput = input;\n return formMessage;\n }\n\n /**\n * Generate form from Zod validation error\n */\n private async generateErrorBasedForm(\n tool: StructuredTool,\n error: ZodError,\n context: FormGenerationContext\n ): Promise<FormMessage> {\n return this.formGenerator.generateFormFromError(\n error,\n tool.schema as z.ZodType<unknown, z.ZodTypeDef, unknown>,\n tool.name,\n context.input ? String(context.input) : ''\n );\n }\n\n /**\n * Validate input against tool schema\n */\n private validateInput(\n tool: StructuredTool,\n input: unknown\n ): { isValid: boolean; errors?: string[] } {\n try {\n const zodSchema = tool.schema as z.ZodType<unknown, z.ZodTypeDef, unknown>;\n zodSchema.parse(input);\n return { isValid: true };\n } catch (error) {\n if (error instanceof ZodError) {\n const errors = error.errors.map(\n (err) => `${err.path.join('.')}: ${err.message}`\n );\n return { isValid: false, errors };\n }\n return { isValid: false, errors: ['Validation failed'] };\n }\n }\n\n /**\n * Check if schema is ZodObject\n */\n private isZodObject(schema: unknown): schema is z.ZodObject<z.ZodRawShape> {\n if (!schema || typeof schema !== 'object') {\n return false;\n }\n const candidate = schema as { _def?: { typeName?: string } };\n return Boolean(candidate._def && candidate._def.typeName === 'ZodObject');\n }\n\n /**\n * Check if tool has render configuration\n */\n private hasRenderConfig(tool: StructuredTool): boolean {\n const schema = tool.schema as Record<string, unknown>;\n return !!(schema && schema._renderConfig);\n }\n\n /**\n * Extract render configuration from tool\n */\n private extractRenderConfig(tool: StructuredTool): Record<string, unknown> | undefined {\n const schema = tool.schema as Record<string, unknown>;\n return schema?._renderConfig as Record<string, unknown> | undefined;\n }\n\n /**\n * Resolve form schema for FormValidatable tools\n */\n private resolveFormSchema(tool: StructuredTool): { \n schemaToUse: z.ZodSchema; \n isFocusedSchema: boolean \n } {\n const formValidatableTool = tool as {\n getFormSchema?: () => z.ZodSchema | null;\n };\n \n if (formValidatableTool.getFormSchema) {\n const focusedSchema = formValidatableTool.getFormSchema();\n if (focusedSchema) {\n return { schemaToUse: focusedSchema, isFocusedSchema: true };\n }\n }\n \n return { schemaToUse: tool.schema as z.ZodSchema, isFocusedSchema: false };\n }\n\n /**\n * Determine missing fields for form generation\n */\n private determineMissingFields(\n tool: StructuredTool,\n input: unknown,\n _schema: z.ZodSchema,\n _isFocusedSchema: boolean\n ): Set<string> {\n const missingFields = new Set<string>();\n \n if (!input || typeof input !== 'object') {\n return missingFields;\n }\n \n const inputRecord = input as Record<string, unknown>;\n const formValidatableTool = tool as {\n isFieldEmpty?: (fieldName: string, value: unknown) => boolean;\n getEssentialFields?: () => string[];\n };\n \n if (formValidatableTool.getEssentialFields) {\n const essentialFields = formValidatableTool.getEssentialFields();\n for (const field of essentialFields) {\n if (!(field in inputRecord) || \n (formValidatableTool.isFieldEmpty && \n formValidatableTool.isFieldEmpty(field, inputRecord[field]))) {\n missingFields.add(field);\n }\n }\n }\n \n return missingFields;\n }\n\n /**\n * Generate form with resolved schema\n */\n private async generateFormWithSchema(\n tool: StructuredTool,\n input: unknown,\n schema: z.ZodSchema,\n missingFields: Set<string>\n ): Promise<FormMessage> {\n const formMessage = await this.formGenerator.generateFormFromSchema(\n schema as z.ZodType<unknown, z.ZodTypeDef, unknown>,\n input,\n {\n toolName: tool.name,\n toolDescription: tool.description\n },\n missingFields\n );\n \n if (this.isZodObject(schema)) {\n try {\n const { jsonSchema, uiSchema } = this.formGenerator.generateJsonSchemaForm(\n schema,\n input as Record<string, unknown> | undefined,\n missingFields\n );\n formMessage.jsonSchema = jsonSchema;\n formMessage.uiSchema = uiSchema;\n } catch (error) {\n this.logger.warn('Failed to generate JSON Schema:', error);\n }\n }\n \n formMessage.partialInput = input;\n return formMessage;\n }\n\n /**\n * Validate form submission\n */\n private validateSubmission(submission: FormSubmission): void {\n if (!submission.toolName) {\n throw new Error('Tool name is required in form submission');\n }\n if (!submission.parameters) {\n throw new Error('Parameters are required in form submission');\n }\n }\n\n /**\n * Extract base tool input from context\n */\n private extractBaseToolInput(context?: {\n originalInput?: Record<string, unknown>;\n }): Record<string, unknown> {\n return context?.originalInput || {};\n }\n\n /**\n * Extract submission data\n */\n private extractSubmissionData(submission: FormSubmission): Record<string, unknown> {\n return {\n ...submission.parameters,\n __fromForm: true\n };\n }\n\n /**\n * Merge input data\n */\n private mergeInputData(\n baseInput: Record<string, unknown>,\n submissionData: Record<string, unknown>\n ): Record<string, unknown> {\n return {\n ...baseInput,\n ...submissionData\n };\n }\n\n /**\n * Get registered strategies\n */\n getRegisteredStrategies(): string[] {\n return ['FormValidatable', 'SchemaBased', 'RenderConfig', 'ZodErrorBased'];\n }\n\n /**\n * Get registered middleware\n */\n getRegisteredMiddleware(): string[] {\n return ['FormSubmissionValidator'];\n }\n}"],"names":[],"mappings":";;;;AAiCO,MAAM,WAAW;AAAA,EAItB,YAAY,QAAiB;AAC3B,SAAK,gBAAgB,IAAI,cAAA;AACzB,SAAK,SAAS,UAAU,IAAI,OAAO,EAAE,QAAQ,cAAc;AAAA,EAC7D;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aACJ,UACA,MACA,OACA,SAC6B;AAC7B,UAAM,cAAqC;AAAA,MACzC;AAAA,MACA;AAAA,MACA,GAAG;AAAA,IAAA;AAGL,QAAI;AACF,UAAI,kBAAkB,IAAI,GAAG;AAC3B,eAAO,MAAM,KAAK,4BAA4B,MAAM,OAAO,WAAW;AAAA,MACxE;AAEA,UAAI,iBAAiB,UAAU;AAC7B,eA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U;AACxB,YAAM,IAAI,MAAM,0CAA0C;AAAA,IAC5D;AACA,QAAI,CAAC,WAAW,YAAY;AAC1B,YAAM,IAAI,MAAM,4CAA4C;AAAA,IAC9D;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,qBAAqB,SAED;AAC1B,WAAO,SAAS,iBAAiB,CAAA;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAKQ,sBAAsB,YAAqD;AACjF,WAAO;AAAA,MACL,GAAG,WAAW;AAAA,MACd,YAAY;AAAA,IAAA;AAAA,EAEhB;AAAA;AAAA;AAAA;AAAA,EAKQ,eACN,WACA,gBACyB;AACzB,WAAO;AAAA,MACL,GAAG;AAAA,MACH,GAAG;AAAA,IAAA;AAAA,EAEP;AAAA;AAAA;AAAA;AAAA,EAKA,0BAAoC;AAClC,WAAO,CAAC,mBAAmB,eAAe,gBAAgB,eAAe;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA,EAKA,0BAAoC;AAClC,WAAO,CAAC,yBAAyB;AAAA,EACnC;AACF;"}
|
package/dist/esm/index30.js
CHANGED
|
@@ -1,95 +1,159 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
constructor(hederaKit) {
|
|
6
|
-
super(hederaKit);
|
|
1
|
+
class FieldTypeRegistry {
|
|
2
|
+
constructor() {
|
|
3
|
+
this.patterns = /* @__PURE__ */ new Map();
|
|
4
|
+
this.initializeDefaultPatterns();
|
|
7
5
|
}
|
|
8
6
|
/**
|
|
9
|
-
*
|
|
7
|
+
* Get singleton instance
|
|
10
8
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
if (!params.transfers || params.transfers.length === 0) {
|
|
15
|
-
throw new Error("HbarTransferParams must include at least one transfer.");
|
|
9
|
+
static getInstance() {
|
|
10
|
+
if (!FieldTypeRegistry.instance) {
|
|
11
|
+
FieldTypeRegistry.instance = new FieldTypeRegistry();
|
|
16
12
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
13
|
+
return FieldTypeRegistry.instance;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Initialize default field type patterns
|
|
17
|
+
*/
|
|
18
|
+
initializeDefaultPatterns() {
|
|
19
|
+
this.register("numeric-supply-exact", {
|
|
20
|
+
pattern: ["maxSupply", "minSupply", "totalSupply"],
|
|
21
|
+
type: "number",
|
|
22
|
+
priority: 15
|
|
23
|
+
});
|
|
24
|
+
this.register("numeric-supply", {
|
|
25
|
+
pattern: /supply$/i,
|
|
26
|
+
type: "number",
|
|
27
|
+
priority: 10
|
|
28
|
+
});
|
|
29
|
+
this.register("numeric-amounts", {
|
|
30
|
+
pattern: /(?:amount|quantity|count|total|sum|value)$/i,
|
|
31
|
+
type: "number",
|
|
32
|
+
priority: 8
|
|
33
|
+
});
|
|
34
|
+
this.register("numeric-time", {
|
|
35
|
+
pattern: /(?:period|duration|time|timeout|delay|interval)$/i,
|
|
36
|
+
type: "number",
|
|
37
|
+
priority: 8
|
|
38
|
+
});
|
|
39
|
+
this.register("numeric-limits", {
|
|
40
|
+
pattern: /(?:limit|max|min|threshold|size|length)$/i,
|
|
41
|
+
type: "number",
|
|
42
|
+
priority: 7
|
|
43
|
+
});
|
|
44
|
+
this.register("currency", {
|
|
45
|
+
pattern: /(?:price|cost|fee|payment|balance|amount)$/i,
|
|
46
|
+
type: "currency",
|
|
47
|
+
priority: 9
|
|
48
|
+
});
|
|
49
|
+
this.register("percentage", {
|
|
50
|
+
pattern: /(?:percent|percentage|rate|ratio)$/i,
|
|
51
|
+
type: "percentage",
|
|
52
|
+
priority: 9
|
|
53
|
+
});
|
|
54
|
+
this.register("boolean-freeze", {
|
|
55
|
+
pattern: ["freezeDefault", "freeze"],
|
|
56
|
+
type: "checkbox",
|
|
57
|
+
priority: 10
|
|
58
|
+
});
|
|
59
|
+
this.register("boolean-flags", {
|
|
60
|
+
pattern: /(?:is|has|can|should|enable|disable|active|default|allow)(?:[A-Z]|$)/,
|
|
61
|
+
type: "checkbox",
|
|
62
|
+
priority: 8
|
|
63
|
+
});
|
|
64
|
+
this.register("textarea", {
|
|
65
|
+
pattern: /(?:memo|description|notes|comment|message|content|body|text)$/i,
|
|
66
|
+
type: "textarea",
|
|
67
|
+
priority: 8
|
|
68
|
+
});
|
|
69
|
+
this.register("array-fees", {
|
|
70
|
+
pattern: ["customFees", "fees"],
|
|
71
|
+
type: "array",
|
|
72
|
+
priority: 10
|
|
73
|
+
});
|
|
74
|
+
this.register("array-general", {
|
|
75
|
+
pattern: /(?:list|items|array|collection)$/i,
|
|
76
|
+
type: "array",
|
|
77
|
+
priority: 7
|
|
78
|
+
});
|
|
79
|
+
this.register("object-options", {
|
|
80
|
+
pattern: ["metaOptions", "options"],
|
|
81
|
+
type: "object",
|
|
82
|
+
priority: 10
|
|
83
|
+
});
|
|
84
|
+
this.register("object-config", {
|
|
85
|
+
pattern: /(?:config|settings|configuration|metadata|data|info)$/i,
|
|
86
|
+
type: "object",
|
|
87
|
+
priority: 7
|
|
88
|
+
});
|
|
89
|
+
this.register("select-type", {
|
|
90
|
+
pattern: /(?:type|kind|category|status|state|mode)$/i,
|
|
91
|
+
type: "select",
|
|
92
|
+
priority: 7
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Register a field type pattern
|
|
97
|
+
*/
|
|
98
|
+
register(key, pattern) {
|
|
99
|
+
this.patterns.set(key, pattern);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Unregister a field type pattern
|
|
103
|
+
*/
|
|
104
|
+
unregister(key) {
|
|
105
|
+
return this.patterns.delete(key);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Detect field type based on field name
|
|
109
|
+
*/
|
|
110
|
+
detectType(fieldName) {
|
|
111
|
+
const matches = [];
|
|
112
|
+
for (const pattern of this.patterns.values()) {
|
|
113
|
+
let isMatch = false;
|
|
114
|
+
if (Array.isArray(pattern.pattern)) {
|
|
115
|
+
isMatch = pattern.pattern.some(
|
|
116
|
+
(p) => fieldName === p || fieldName.toLowerCase() === p.toLowerCase()
|
|
37
117
|
);
|
|
38
|
-
|
|
118
|
+
} else if (pattern.pattern instanceof RegExp) {
|
|
119
|
+
isMatch = pattern.pattern.test(fieldName);
|
|
39
120
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
const accountId = typeof transferInput.accountId === "string" ? AccountId.fromString(transferInput.accountId) : transferInput.accountId;
|
|
45
|
-
const amountValue = typeof transferInput.amount === "string" || typeof transferInput.amount === "number" ? transferInput.amount : transferInput.amount.toString();
|
|
46
|
-
const amountBigNum = new BigNumber(amountValue);
|
|
47
|
-
const roundedAmount = amountBigNum.toFixed(8, BigNumber.ROUND_DOWN);
|
|
48
|
-
this.logger.info(
|
|
49
|
-
`Processing transfer: ${amountValue} HBAR (rounded to ${roundedAmount}) for account ${accountId.toString()}`
|
|
50
|
-
);
|
|
51
|
-
const sdkHbarAmount = Hbar.fromString(roundedAmount);
|
|
52
|
-
processedTransfers.push({
|
|
53
|
-
accountId,
|
|
54
|
-
amount: amountBigNum,
|
|
55
|
-
hbar: sdkHbarAmount
|
|
121
|
+
if (isMatch) {
|
|
122
|
+
matches.push({
|
|
123
|
+
type: pattern.type,
|
|
124
|
+
priority: pattern.priority ?? 5
|
|
56
125
|
});
|
|
57
|
-
const tinybarsContribution = sdkHbarAmount.toTinybars();
|
|
58
|
-
netZeroInTinybars = netZeroInTinybars.plus(
|
|
59
|
-
tinybarsContribution.toString()
|
|
60
|
-
);
|
|
61
|
-
}
|
|
62
|
-
if (!netZeroInTinybars.isZero()) {
|
|
63
|
-
this.logger.warn(
|
|
64
|
-
`Transfer sum not zero: ${netZeroInTinybars.toString()} tinybars off. Adjusting last transfer.`
|
|
65
|
-
);
|
|
66
|
-
if (processedTransfers.length > 0) {
|
|
67
|
-
const lastTransfer = processedTransfers[processedTransfers.length - 1];
|
|
68
|
-
const adjustment = netZeroInTinybars.dividedBy(-1e8);
|
|
69
|
-
const adjustedAmount = lastTransfer.amount.plus(adjustment);
|
|
70
|
-
const adjustedRounded = adjustedAmount.toFixed(8, BigNumber.ROUND_DOWN);
|
|
71
|
-
lastTransfer.hbar = Hbar.fromString(adjustedRounded);
|
|
72
|
-
this.logger.info(
|
|
73
|
-
`Adjusted last transfer for ${lastTransfer.accountId.toString()} to ${adjustedRounded} HBAR`
|
|
74
|
-
);
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
for (const transfer of processedTransfers) {
|
|
78
|
-
transaction.addHbarTransfer(transfer.accountId, transfer.hbar);
|
|
79
126
|
}
|
|
80
127
|
}
|
|
81
|
-
if (
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
} else {
|
|
85
|
-
transaction.setTransactionMemo(params.memo);
|
|
86
|
-
}
|
|
128
|
+
if (matches.length > 0) {
|
|
129
|
+
matches.sort((a, b) => b.priority - a.priority);
|
|
130
|
+
return matches[0].type;
|
|
87
131
|
}
|
|
88
|
-
|
|
89
|
-
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Get all registered patterns
|
|
136
|
+
*/
|
|
137
|
+
getPatterns() {
|
|
138
|
+
return new Map(this.patterns);
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Clear all patterns
|
|
142
|
+
*/
|
|
143
|
+
clear() {
|
|
144
|
+
this.patterns.clear();
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Reset to default patterns
|
|
148
|
+
*/
|
|
149
|
+
reset() {
|
|
150
|
+
this.clear();
|
|
151
|
+
this.initializeDefaultPatterns();
|
|
90
152
|
}
|
|
91
153
|
}
|
|
154
|
+
const fieldTypeRegistry = FieldTypeRegistry.getInstance();
|
|
92
155
|
export {
|
|
93
|
-
|
|
156
|
+
FieldTypeRegistry,
|
|
157
|
+
fieldTypeRegistry
|
|
94
158
|
};
|
|
95
159
|
//# sourceMappingURL=index30.js.map
|
package/dist/esm/index30.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index30.js","sources":["../../src/
|
|
1
|
+
{"version":3,"file":"index30.js","sources":["../../src/forms/field-type-registry.ts"],"sourcesContent":["/**\n * Registry for field type detection patterns\n * @module FieldTypeRegistry\n */\n\nimport type { FormFieldType } from './types';\n\n/**\n * Pattern-based field type detection rule\n */\nexport interface FieldTypePattern {\n pattern: RegExp | string[];\n type: FormFieldType;\n priority?: number;\n}\n\n/**\n * Registry for managing field type detection patterns\n */\nexport class FieldTypeRegistry {\n private static instance: FieldTypeRegistry;\n private patterns: Map<string, FieldTypePattern> = new Map();\n \n private constructor() {\n this.initializeDefaultPatterns();\n }\n \n /**\n * Get singleton instance\n */\n static getInstance(): FieldTypeRegistry {\n if (!FieldTypeRegistry.instance) {\n FieldTypeRegistry.instance = new FieldTypeRegistry();\n }\n return FieldTypeRegistry.instance;\n }\n \n /**\n * Initialize default field type patterns\n */\n private initializeDefaultPatterns(): void {\n this.register('numeric-supply-exact', {\n pattern: ['maxSupply', 'minSupply', 'totalSupply'],\n type: 'number',\n priority: 15\n });\n \n this.register('numeric-supply', {\n pattern: /supply$/i,\n type: 'number',\n priority: 10\n });\n \n this.register('numeric-amounts', {\n pattern: /(?:amount|quantity|count|total|sum|value)$/i,\n type: 'number',\n priority: 8\n });\n \n this.register('numeric-time', {\n pattern: /(?:period|duration|time|timeout|delay|interval)$/i,\n type: 'number',\n priority: 8\n });\n \n this.register('numeric-limits', {\n pattern: /(?:limit|max|min|threshold|size|length)$/i,\n type: 'number',\n priority: 7\n });\n \n this.register('currency', {\n pattern: /(?:price|cost|fee|payment|balance|amount)$/i,\n type: 'currency',\n priority: 9\n });\n \n this.register('percentage', {\n pattern: /(?:percent|percentage|rate|ratio)$/i,\n type: 'percentage',\n priority: 9\n });\n \n this.register('boolean-freeze', {\n pattern: ['freezeDefault', 'freeze'],\n type: 'checkbox',\n priority: 10\n });\n \n this.register('boolean-flags', {\n pattern: /(?:is|has|can|should|enable|disable|active|default|allow)(?:[A-Z]|$)/,\n type: 'checkbox',\n priority: 8\n });\n \n this.register('textarea', {\n pattern: /(?:memo|description|notes|comment|message|content|body|text)$/i,\n type: 'textarea',\n priority: 8\n });\n \n this.register('array-fees', {\n pattern: ['customFees', 'fees'],\n type: 'array',\n priority: 10\n });\n \n this.register('array-general', {\n pattern: /(?:list|items|array|collection)$/i,\n type: 'array',\n priority: 7\n });\n \n this.register('object-options', {\n pattern: ['metaOptions', 'options'],\n type: 'object',\n priority: 10\n });\n \n this.register('object-config', {\n pattern: /(?:config|settings|configuration|metadata|data|info)$/i,\n type: 'object',\n priority: 7\n });\n \n this.register('select-type', {\n pattern: /(?:type|kind|category|status|state|mode)$/i,\n type: 'select',\n priority: 7\n });\n }\n \n /**\n * Register a field type pattern\n */\n register(key: string, pattern: FieldTypePattern): void {\n this.patterns.set(key, pattern);\n }\n \n /**\n * Unregister a field type pattern\n */\n unregister(key: string): boolean {\n return this.patterns.delete(key);\n }\n \n /**\n * Detect field type based on field name\n */\n detectType(fieldName: string): FormFieldType | null {\n const matches: Array<{ type: FormFieldType; priority: number }> = [];\n \n for (const pattern of this.patterns.values()) {\n let isMatch = false;\n \n if (Array.isArray(pattern.pattern)) {\n isMatch = pattern.pattern.some(p => \n fieldName === p || fieldName.toLowerCase() === p.toLowerCase()\n );\n } else if (pattern.pattern instanceof RegExp) {\n isMatch = pattern.pattern.test(fieldName);\n }\n \n if (isMatch) {\n matches.push({\n type: pattern.type,\n priority: pattern.priority ?? 5\n });\n }\n }\n \n if (matches.length > 0) {\n matches.sort((a, b) => b.priority - a.priority);\n return matches[0].type;\n }\n \n return null;\n }\n \n /**\n * Get all registered patterns\n */\n getPatterns(): Map<string, FieldTypePattern> {\n return new Map(this.patterns);\n }\n \n /**\n * Clear all patterns\n */\n clear(): void {\n this.patterns.clear();\n }\n \n /**\n * Reset to default patterns\n */\n reset(): void {\n this.clear();\n this.initializeDefaultPatterns();\n }\n}\n\nexport const fieldTypeRegistry = FieldTypeRegistry.getInstance();"],"names":[],"mappings":"AAmBO,MAAM,kBAAkB;AAAA,EAIrB,cAAc;AAFtB,SAAQ,+BAA8C,IAAA;AAGpD,SAAK,0BAAA;AAAA,EACP;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,cAAiC;AACtC,QAAI,CAAC,kBAAkB,UAAU;AAC/B,wBAAkB,WAAW,IAAI,kBAAA;AAAA,IACnC;AACA,WAAO,kBAAkB;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKQ,4BAAkC;AACxC,SAAK,SAAS,wBAAwB;AAAA,MACpC,SAAS,CAAC,aAAa,aAAa,aAAa;AAAA,MACjD,MAAM;AAAA,MACN,UAAU;AAAA,IAAA,CACX;AAED,SAAK,SAAS,kBAAkB;AAAA,MAC9B,SAAS;AAAA,MACT,MAAM;AAAA,MACN,UAAU;AAAA,IAAA,CACX;AAED,SAAK,SAAS,mBAAmB;AAAA,MAC/B,SAAS;AAAA,MACT,MAAM;AAAA,MACN,UAAU;AAAA,IAAA,CACX;AAED,SAAK,SAAS,gBAAgB;AAAA,MAC5B,SAAS;AAAA,MACT,MAAM;AAAA,MACN,UAAU;AAAA,IAAA,CACX;AAED,SAAK,SAAS,kBAAkB;AAAA,MAC9B,SAAS;AAAA,MACT,MAAM;AAAA,MACN,UAAU;AAAA,IAAA,CACX;AAED,SAAK,SAAS,YAAY;AAAA,MACxB,SAAS;AAAA,MACT,MAAM;AAAA,MACN,UAAU;AAAA,IAAA,CACX;AAED,SAAK,SAAS,cAAc;AAAA,MAC1B,SAAS;AAAA,MACT,MAAM;AAAA,MACN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,QAAQ;AAAA,UAAK,OAC7B,cAAc,KAAK,UAAU,YAAA,MAAkB,EAAE,YAAA;AAAA,QAAY;AAAA,MAEjE,WAAW,QAAQ,mBAAmB,QAAQ;AAC5C,kBAAU,QAAQ,QAAQ,KAAK,SAAS;AAAA,MAC1C;AAEA,UAAI,SAAS;AACX,gBAAQ,KAAK;AAAA,UACX,MAAM,QAAQ;AAAA,UACd,UAAU,QAAQ,YAAY;AAAA,QAAA,CAC/B;AAAA,MACH;AAAA,IACF;AAEA,QAAI,QAAQ,SAAS,GAAG;AACtB,cAAQ,KAAK,CAAC,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;AAC9C,aAAO,QAAQ,CAAC,EAAE;AAAA,IACpB;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,cAA6C;AAC3C,WAAO,IAAI,IAAI,KAAK,QAAQ;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,SAAK,SAAS,MAAA;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,SAAK,MAAA;AACL,SAAK,0BAAA;AAAA,EACP;AACF;AAEO,MAAM,oBAAoB,kBAAkB,YAAA;"}
|
package/dist/esm/index31.js
CHANGED
|
@@ -1,12 +1,68 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import { createHash } from "crypto";
|
|
2
|
+
class ReferenceIdGenerator {
|
|
3
|
+
/**
|
|
4
|
+
* Generate a content-based reference ID using SHA-256 hashing
|
|
5
|
+
*
|
|
6
|
+
* @param content The content to generate a reference ID for
|
|
7
|
+
* @returns Deterministic reference ID based on content hash
|
|
8
|
+
*/
|
|
9
|
+
static generateId(content) {
|
|
10
|
+
const hash = createHash("sha256");
|
|
11
|
+
hash.update(content);
|
|
12
|
+
return hash.digest("hex");
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Validate that a string is a properly formatted reference ID
|
|
16
|
+
*
|
|
17
|
+
* @param id The ID to validate
|
|
18
|
+
* @returns true if the ID is valid format
|
|
19
|
+
*/
|
|
20
|
+
static isValidReferenceId(id) {
|
|
21
|
+
if (!id || typeof id !== "string") {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
if (id.length !== 64) {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
return /^[a-f0-9]+$/.test(id);
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Extract reference ID from ref:// format
|
|
31
|
+
*
|
|
32
|
+
* @param input Input string that may contain a reference ID
|
|
33
|
+
* @returns Extracted reference ID or null if not found
|
|
34
|
+
*/
|
|
35
|
+
static extractReferenceId(input) {
|
|
36
|
+
if (!input || typeof input !== "string") {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
const refFormatMatch = input.match(/^ref:\/\/([a-f0-9]{64})$/);
|
|
40
|
+
if (refFormatMatch) {
|
|
41
|
+
return refFormatMatch[1];
|
|
42
|
+
}
|
|
43
|
+
return this.isValidReferenceId(input) ? input : null;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Format a reference ID in the standard ref:// format
|
|
47
|
+
*
|
|
48
|
+
* @param referenceId The reference ID to format
|
|
49
|
+
* @returns Formatted reference string
|
|
50
|
+
*/
|
|
51
|
+
static formatReference(referenceId) {
|
|
52
|
+
return `ref://${referenceId}`;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Generate a test reference ID (for testing purposes only)
|
|
56
|
+
*
|
|
57
|
+
* @param testSeed A test seed to generate a fake but valid ID format
|
|
58
|
+
* @returns A valid format reference ID for testing
|
|
59
|
+
*/
|
|
60
|
+
static generateTestId(testSeed) {
|
|
61
|
+
const content = Buffer.from(`test-${testSeed}-${Date.now()}`);
|
|
62
|
+
return this.generateId(content);
|
|
7
63
|
}
|
|
8
64
|
}
|
|
9
65
|
export {
|
|
10
|
-
|
|
66
|
+
ReferenceIdGenerator
|
|
11
67
|
};
|
|
12
68
|
//# sourceMappingURL=index31.js.map
|
package/dist/esm/index31.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index31.js","sources":["../../src/
|
|
1
|
+
{"version":3,"file":"index31.js","sources":["../../src/memory/ReferenceIdGenerator.ts"],"sourcesContent":["import { createHash } from 'crypto';\nimport { ReferenceId } from '../types/content-reference';\n\n/**\n * Content-based reference ID generator using SHA-256 (HCS-1 style)\n * \n * Generates deterministic reference IDs based on content hashing.\n * Same content always produces the same reference ID.\n */\nexport class ReferenceIdGenerator {\n /**\n * Generate a content-based reference ID using SHA-256 hashing\n * \n * @param content The content to generate a reference ID for\n * @returns Deterministic reference ID based on content hash\n */\n static generateId(content: Buffer): ReferenceId {\n const hash = createHash('sha256');\n hash.update(content);\n return hash.digest('hex');\n }\n \n /**\n * Validate that a string is a properly formatted reference ID\n * \n * @param id The ID to validate\n * @returns true if the ID is valid format\n */\n static isValidReferenceId(id: string): id is ReferenceId {\n if (!id || typeof id !== 'string') {\n return false;\n }\n \n if (id.length !== 64) {\n return false;\n }\n \n return /^[a-f0-9]+$/.test(id);\n }\n \n /**\n * Extract reference ID from ref:// format\n * \n * @param input Input string that may contain a reference ID\n * @returns Extracted reference ID or null if not found\n */\n static extractReferenceId(input: string): ReferenceId | null {\n if (!input || typeof input !== 'string') {\n return null;\n }\n \n const refFormatMatch = input.match(/^ref:\\/\\/([a-f0-9]{64})$/);\n if (refFormatMatch) {\n return refFormatMatch[1] as ReferenceId;\n }\n \n return this.isValidReferenceId(input) ? input : null;\n }\n \n /**\n * Format a reference ID in the standard ref:// format\n * \n * @param referenceId The reference ID to format\n * @returns Formatted reference string\n */\n static formatReference(referenceId: ReferenceId): string {\n return `ref://${referenceId}`;\n }\n \n /**\n * Generate a test reference ID (for testing purposes only)\n * \n * @param testSeed A test seed to generate a fake but valid ID format\n * @returns A valid format reference ID for testing\n */\n static generateTestId(testSeed: string): ReferenceId {\n const content = Buffer.from(`test-${testSeed}-${Date.now()}`);\n return this.generateId(content);\n }\n}"],"names":[],"mappings":";AASO,MAAM,qBAAqB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhC,OAAO,WAAW,SAA8B;AAC9C,UAAM,OAAO,WAAW,QAAQ;AAChC,SAAK,OAAO,OAAO;AACnB,WAAO,KAAK,OAAO,KAAK;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,mBAAmB,IAA+B;AACvD,QAAI,CAAC,MAAM,OAAO,OAAO,UAAU;AACjC,aAAO;AAAA,IACT;AAEA,QAAI,GAAG,WAAW,IAAI;AACpB,aAAO;AAAA,IACT;AAEA,WAAO,cAAc,KAAK,EAAE;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,mBAAmB,OAAmC;AAC3D,QAAI,CAAC,SAAS,OAAO,UAAU,UAAU;AACvC,aAAO;AAAA,IACT;AAEA,UAAM,iBAAiB,MAAM,MAAM,0BAA0B;AAC7D,QAAI,gBAAgB;AAClB,aAAO,eAAe,CAAC;AAAA,IACzB;AAEA,WAAO,KAAK,mBAAmB,KAAK,IAAI,QAAQ;AAAA,EAClD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,gBAAgB,aAAkC;AACvD,WAAO,SAAS,WAAW;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,eAAe,UAA+B;AACnD,UAAM,UAAU,OAAO,KAAK,QAAQ,QAAQ,IAAI,KAAK,IAAA,CAAK,EAAE;AAC5D,WAAO,KAAK,WAAW,OAAO;AAAA,EAChC;AACF;"}
|