tjs-lang 0.6.45 → 0.7.4
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/CLAUDE.md +70 -444
- package/README.md +15 -82
- package/bin/benchmarks.ts +7 -7
- package/bin/dev.ts +2 -1
- package/demo/autocomplete.test.ts +1 -1
- package/demo/docs.json +743 -47
- package/demo/src/demo-nav.ts +5 -5
- package/demo/src/index.ts +28 -36
- package/demo/src/module-sw.ts +1 -1
- package/demo/src/playground-shared.ts +17 -17
- package/demo/src/playground.ts +13 -1
- package/demo/src/style.ts +4 -1
- package/demo/src/tjs-playground.ts +5 -5
- package/demo/src/user-store.ts +2 -1
- package/demo/static/favicon.svg +17 -24
- package/demo/static/tosi-platform.json +9304 -0
- package/dist/index.js +176 -175
- package/dist/index.js.map +5 -43
- package/dist/scripts/compat-effect.d.ts +16 -0
- package/dist/scripts/compat-kysely.d.ts +13 -0
- package/dist/scripts/compat-radash.d.ts +13 -0
- package/dist/scripts/compat-superstruct.d.ts +13 -0
- package/dist/scripts/compat-ts-pattern.d.ts +13 -0
- package/dist/scripts/compat-zod.d.ts +12 -0
- package/dist/src/lang/emitters/from-ts.d.ts +1 -1
- package/dist/src/lang/emitters/js-tests.d.ts +4 -0
- package/dist/src/lang/emitters/js.d.ts +2 -2
- package/dist/src/lang/index.d.ts +1 -0
- package/dist/src/lang/json-schema.d.ts +40 -0
- package/dist/src/lang/parser-transforms.d.ts +14 -0
- package/dist/src/lang/runtime.d.ts +39 -20
- package/dist/src/types/Type.d.ts +5 -0
- package/dist/tjs-batteries.js +3 -4
- package/dist/tjs-batteries.js.map +5 -13
- package/dist/tjs-eval.js +47 -0
- package/dist/tjs-eval.js.map +7 -0
- package/dist/tjs-from-ts.js +58 -0
- package/dist/tjs-from-ts.js.map +7 -0
- package/dist/tjs-lang.js +349 -0
- package/dist/tjs-lang.js.map +7 -0
- package/dist/tjs-vm.js +51 -51
- package/dist/tjs-vm.js.map +4 -19
- package/docs/README.md +21 -20
- package/docs/WASM-QUICKSTART.md +283 -0
- package/docs/diagrams/architecture-shift.svg +117 -0
- package/docs/diagrams/compile-runtime.svg +130 -0
- package/docs/diagrams/icon-riff-1.svg +55 -0
- package/docs/diagrams/icon-riff-2.svg +62 -0
- package/docs/diagrams/icon-riff-3.svg +61 -0
- package/docs/diagrams/platform-overview.svg +114 -0
- package/docs/diagrams/safe-eval.svg +147 -0
- package/docs/eval-v4/arch-comparison.svg +277 -0
- package/docs/eval-v4/bundler-tree.svg +250 -0
- package/docs/eval-v4/http-lifecycle.svg +148 -0
- package/docs/function-predicate-design.md +8 -8
- package/docs/native-engine-integration.md +2 -2
- package/editors/codemirror/autocomplete.test.ts +29 -29
- package/package.json +24 -12
- package/src/cli/commands/convert.test.ts +11 -8
- package/src/lang/codegen.test.ts +117 -112
- package/src/lang/docs.test.ts +22 -22
- package/src/lang/docs.ts +5 -8
- package/src/lang/emitters/dts.test.ts +13 -13
- package/src/lang/emitters/from-ts.ts +36 -9
- package/src/lang/emitters/js-tests.ts +143 -28
- package/src/lang/emitters/js.ts +44 -31
- package/src/lang/features.test.ts +259 -43
- package/src/lang/from-ts.test.ts +3 -3
- package/src/lang/function-predicate.test.ts +1 -1
- package/src/lang/index.ts +8 -47
- package/src/lang/json-schema.test.ts +261 -0
- package/src/lang/json-schema.ts +167 -0
- package/src/lang/parser-params.ts +28 -44
- package/src/lang/parser-transforms.ts +255 -0
- package/src/lang/parser.test.ts +32 -13
- package/src/lang/parser.ts +49 -11
- package/src/lang/perf.test.ts +11 -11
- package/src/lang/roundtrip.test.ts +3 -3
- package/src/lang/runtime.test.ts +167 -0
- package/src/lang/runtime.ts +213 -64
- package/src/lang/transpiler.test.ts +21 -21
- package/src/lang/typescript-syntax.test.ts +11 -9
- package/src/types/Type.ts +38 -1
- package/src/use-cases/bootstrap.test.ts +7 -7
- package/src/use-cases/client-server.test.ts +1 -1
- package/src/use-cases/malicious-actor.test.ts +1 -1
- package/src/use-cases/rag-processor.test.ts +1 -1
- package/src/use-cases/sophisticated-agents.test.ts +2 -2
- package/src/use-cases/transpiler-llm.test.ts +1 -1
- package/src/use-cases/unbundled-imports.test.ts +9 -9
- package/tjs-lang.svg +17 -25
- package/dist/tjs-full.js +0 -435
- package/dist/tjs-full.js.map +0 -45
- package/dist/tjs-transpiler.js +0 -3
- package/dist/tjs-transpiler.js.map +0 -11
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* Effect Compatibility Test
|
|
4
|
+
*
|
|
5
|
+
* Clones Effect (the "final boss" of TypeScript complexity), transpiles
|
|
6
|
+
* its source using fromTS, and attempts to run its Vitest suite.
|
|
7
|
+
*
|
|
8
|
+
* Effect uses higher-kinded types, massive intersections, and the most
|
|
9
|
+
* advanced TypeScript patterns in the wild.
|
|
10
|
+
*
|
|
11
|
+
* Usage:
|
|
12
|
+
* bun scripts/compat-effect.ts
|
|
13
|
+
* bun scripts/compat-effect.ts --clean
|
|
14
|
+
* bun scripts/compat-effect.ts --test # Also run tests (requires pnpm)
|
|
15
|
+
*/
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* Kysely Compatibility Test
|
|
4
|
+
*
|
|
5
|
+
* Clones Kysely, transpiles its TS source using TJS's fromTS.
|
|
6
|
+
* Kysely's tests require database connections so we only verify
|
|
7
|
+
* that all source files transpile without error.
|
|
8
|
+
*
|
|
9
|
+
* Usage:
|
|
10
|
+
* bun scripts/compat-kysely.ts
|
|
11
|
+
* bun scripts/compat-kysely.ts --clean
|
|
12
|
+
*/
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* Radash Compatibility Test
|
|
4
|
+
*
|
|
5
|
+
* Clones Radash, transpiles its TypeScript source using TJS's fromTS,
|
|
6
|
+
* and runs Radash's own test suite to verify compatibility.
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* bun scripts/compat-radash.ts # Direct mode (fromTS → JS)
|
|
10
|
+
* bun scripts/compat-radash.ts --full # Full pipeline (fromTS → TJS → JS)
|
|
11
|
+
* bun scripts/compat-radash.ts --clean # Remove clone and start fresh
|
|
12
|
+
*/
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* Superstruct Compatibility Test
|
|
4
|
+
*
|
|
5
|
+
* Clones Superstruct, transpiles its TS source using TJS's fromTS,
|
|
6
|
+
* and runs Superstruct's own test suite to verify compatibility.
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* bun scripts/compat-superstruct.ts # Direct mode (fromTS → JS)
|
|
10
|
+
* bun scripts/compat-superstruct.ts --full # Full pipeline (fromTS → TJS → JS)
|
|
11
|
+
* bun scripts/compat-superstruct.ts --clean # Remove clone and start fresh
|
|
12
|
+
*/
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* ts-pattern Compatibility Test
|
|
4
|
+
*
|
|
5
|
+
* Clones ts-pattern, transpiles its TS source using TJS's fromTS,
|
|
6
|
+
* and runs ts-pattern's own test suite to verify compatibility.
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* bun scripts/compat-ts-pattern.ts # Direct mode (fromTS → JS)
|
|
10
|
+
* bun scripts/compat-ts-pattern.ts --full # Full pipeline (fromTS → TJS → JS)
|
|
11
|
+
* bun scripts/compat-ts-pattern.ts --clean # Remove clone and start fresh
|
|
12
|
+
*/
|
|
13
|
+
export {};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
/**
|
|
3
|
+
* Zod Compatibility Test
|
|
4
|
+
*
|
|
5
|
+
* Clones Zod (monorepo), transpiles its TS source using TJS's fromTS,
|
|
6
|
+
* and runs Zod's own test suite to verify compatibility.
|
|
7
|
+
*
|
|
8
|
+
* Usage:
|
|
9
|
+
* bun scripts/compat-zod.ts # Direct mode (fromTS → JS)
|
|
10
|
+
* bun scripts/compat-zod.ts --clean # Remove clone and start fresh
|
|
11
|
+
*/
|
|
12
|
+
export {};
|
|
@@ -49,6 +49,10 @@ interface SignatureTestInfo {
|
|
|
49
49
|
defaults?: Record<string, unknown>;
|
|
50
50
|
line: number;
|
|
51
51
|
isAsync?: boolean;
|
|
52
|
+
/** For class method tests: the class name */
|
|
53
|
+
className?: string;
|
|
54
|
+
/** For class method tests: args to pass to the first constructor */
|
|
55
|
+
constructorArgs?: unknown[];
|
|
52
56
|
}
|
|
53
57
|
/**
|
|
54
58
|
* Extract signature test info from source without executing
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Unlike the AST emitter (for AgentJS), this outputs executable JS code.
|
|
6
6
|
*
|
|
7
7
|
* Input:
|
|
8
|
-
* function greet(name: 'world')
|
|
8
|
+
* function greet(name: 'world'): '' {
|
|
9
9
|
* return `Hello, ${name}!`
|
|
10
10
|
* }
|
|
11
11
|
*
|
|
@@ -135,7 +135,7 @@ interface SafetyOptions {
|
|
|
135
135
|
unsafe?: boolean;
|
|
136
136
|
/** Function marked with (?) - always validate inputs */
|
|
137
137
|
safe?: boolean;
|
|
138
|
-
/** Return type safety: 'safe' (
|
|
138
|
+
/** Return type safety: 'safe' (:?) or 'unsafe' (:!) */
|
|
139
139
|
returnSafety?: 'safe' | 'unsafe';
|
|
140
140
|
}
|
|
141
141
|
/**
|
package/dist/src/lang/index.d.ts
CHANGED
|
@@ -30,6 +30,7 @@ export { generateDTS, typeDescriptorToTS, type GenerateDTSOptions, } from './emi
|
|
|
30
30
|
export { fromTS, type FromTSOptions, type FromTSResult, } from './emitters/from-ts';
|
|
31
31
|
export * from './inference';
|
|
32
32
|
export { Schema } from './schema';
|
|
33
|
+
export { typeDescriptorToJSONSchema, exampleToJSONSchema, functionMetaToJSONSchema, type JSONSchemaObject, } from './json-schema';
|
|
33
34
|
export { MetadataCache, getGlobalCache, setGlobalCache } from './metadata-cache';
|
|
34
35
|
export { lint, type LintResult, type LintDiagnostic, type LintOptions, } from './linter';
|
|
35
36
|
export { generateDocs, generateDocsMarkdown, type DocResult, type DocItem, type FunctionTypeInfo, type ParamTypeInfo, } from './docs';
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON Schema generation from TJS TypeDescriptors and example values
|
|
3
|
+
*
|
|
4
|
+
* Converts TJS type information into standard JSON Schema (draft 2020-12).
|
|
5
|
+
*/
|
|
6
|
+
import type { TypeDescriptor } from './types';
|
|
7
|
+
export interface JSONSchemaObject {
|
|
8
|
+
type?: string | string[];
|
|
9
|
+
properties?: Record<string, JSONSchemaObject>;
|
|
10
|
+
items?: JSONSchemaObject | JSONSchemaObject[];
|
|
11
|
+
required?: string[];
|
|
12
|
+
additionalProperties?: boolean;
|
|
13
|
+
anyOf?: JSONSchemaObject[];
|
|
14
|
+
minimum?: number;
|
|
15
|
+
examples?: unknown[];
|
|
16
|
+
description?: string;
|
|
17
|
+
[key: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Convert a TypeDescriptor to JSON Schema
|
|
21
|
+
*/
|
|
22
|
+
export declare function typeDescriptorToJSONSchema(td: TypeDescriptor): JSONSchemaObject;
|
|
23
|
+
/**
|
|
24
|
+
* Infer a JSON Schema from an example value (without going through TypeDescriptor)
|
|
25
|
+
*/
|
|
26
|
+
export declare function exampleToJSONSchema(value: unknown): JSONSchemaObject;
|
|
27
|
+
/**
|
|
28
|
+
* Generate JSON Schema for function parameters (as an object schema)
|
|
29
|
+
* and return type from __tjs metadata
|
|
30
|
+
*/
|
|
31
|
+
export declare function functionMetaToJSONSchema(meta: {
|
|
32
|
+
params: Record<string, any>;
|
|
33
|
+
returns?: {
|
|
34
|
+
type: any;
|
|
35
|
+
example?: any;
|
|
36
|
+
};
|
|
37
|
+
}): {
|
|
38
|
+
input: JSONSchemaObject;
|
|
39
|
+
output?: JSONSchemaObject;
|
|
40
|
+
};
|
|
@@ -295,3 +295,17 @@ export declare function validateNoDate(source: string): string;
|
|
|
295
295
|
export declare function transformConstBang(source: string): string;
|
|
296
296
|
export declare function validateNoVar(source: string): string;
|
|
297
297
|
export declare function validateNoEval(source: string): string;
|
|
298
|
+
/**
|
|
299
|
+
* Transform bang access (!.) to __tjs.bang() calls.
|
|
300
|
+
*
|
|
301
|
+
* x!.foo → __tjs.bang(x,'foo')
|
|
302
|
+
* x.y!.foo → __tjs.bang(x.y,'foo')
|
|
303
|
+
* fn()!.foo → __tjs.bang(fn(),'foo')
|
|
304
|
+
* arr[0]!.foo → __tjs.bang(arr[0],'foo')
|
|
305
|
+
* x!.foo!.bar → __tjs.bang(__tjs.bang(x,'foo'),'bar')
|
|
306
|
+
*
|
|
307
|
+
* If the source is null/undefined, returns MonadicError.
|
|
308
|
+
* If the source is a MonadicError, propagates it.
|
|
309
|
+
* Otherwise, performs a bare property access (throws as usual).
|
|
310
|
+
*/
|
|
311
|
+
export declare function transformBangAccess(source: string): string;
|
|
@@ -107,8 +107,18 @@ export interface TJSConfig {
|
|
|
107
107
|
safety?: SafetyLevel;
|
|
108
108
|
/** Require explicit return types (error if -> not specified) */
|
|
109
109
|
requireReturnTypes?: boolean;
|
|
110
|
-
/**
|
|
110
|
+
/** Track call stacks for error diagnostics (default: false).
|
|
111
|
+
* Useful for server-side logging and agent debugging without devtools.
|
|
112
|
+
* Uses a fixed ring buffer — no allocation pressure. */
|
|
113
|
+
callStacks?: boolean;
|
|
114
|
+
/** Ring buffer size for call stack tracking (default: 64) */
|
|
111
115
|
maxStackSize?: number;
|
|
116
|
+
/** Track recent type errors in a ring buffer (default: true).
|
|
117
|
+
* Zero cost on happy path — only writes when an error occurs.
|
|
118
|
+
* Lets you catch monadic errors that were silently ignored. */
|
|
119
|
+
trackErrors?: boolean;
|
|
120
|
+
/** Ring buffer size for error tracking (default: 64) */
|
|
121
|
+
maxErrors?: number;
|
|
112
122
|
/** Log type errors to console.error when they occur (default: false) */
|
|
113
123
|
logTypeErrors?: boolean;
|
|
114
124
|
/** Throw type errors instead of returning them (default: false).
|
|
@@ -137,22 +147,37 @@ export declare function configure(options: TJSConfig): void;
|
|
|
137
147
|
*/
|
|
138
148
|
export declare function getConfig(): TJSConfig;
|
|
139
149
|
/**
|
|
140
|
-
* Push a function onto the call stack
|
|
141
|
-
*
|
|
150
|
+
* Push a function onto the call stack ring buffer.
|
|
151
|
+
* Only tracks when callStacks or debug is enabled.
|
|
152
|
+
* O(1), no allocation.
|
|
142
153
|
*/
|
|
143
154
|
export declare function pushStack(name: string): void;
|
|
144
155
|
/**
|
|
145
|
-
* Pop a function from the call stack
|
|
156
|
+
* Pop a function from the call stack ring buffer.
|
|
157
|
+
* O(1), no allocation.
|
|
146
158
|
*/
|
|
147
159
|
export declare function popStack(): void;
|
|
148
160
|
/**
|
|
149
|
-
* Get current call stack snapshot
|
|
161
|
+
* Get current call stack snapshot (most recent entries, newest last)
|
|
150
162
|
*/
|
|
151
163
|
export declare function getStack(): string[];
|
|
164
|
+
/**
|
|
165
|
+
* Get recent type errors (newest last).
|
|
166
|
+
* Only tracks when trackErrors is enabled (default: true).
|
|
167
|
+
*/
|
|
168
|
+
export declare function errors(): MonadicError[];
|
|
169
|
+
/**
|
|
170
|
+
* Clear error history. Returns the cleared errors.
|
|
171
|
+
*/
|
|
172
|
+
export declare function clearErrors(): MonadicError[];
|
|
173
|
+
/**
|
|
174
|
+
* Total error count since last clear (may exceed buffer size).
|
|
175
|
+
*/
|
|
176
|
+
export declare function getErrorCount(): number;
|
|
152
177
|
/**
|
|
153
178
|
* Reset runtime state to defaults
|
|
154
179
|
*
|
|
155
|
-
* Resets: config, callStack, unsafeDepth
|
|
180
|
+
* Resets: config, callStack, errors, unsafeDepth
|
|
156
181
|
* Use this in test teardown to prevent state leaking between tests.
|
|
157
182
|
*/
|
|
158
183
|
export declare function resetRuntime(): void;
|
|
@@ -197,18 +222,6 @@ export declare function IsNot(a: unknown, b: unknown): boolean;
|
|
|
197
222
|
* Usage: `typeof x` with TjsEquals transforms to `TypeOf(x)`
|
|
198
223
|
*/
|
|
199
224
|
export declare function TypeOf(value: unknown): string;
|
|
200
|
-
/**
|
|
201
|
-
* Check if a number is bounded (finite and not NaN).
|
|
202
|
-
* The question you're actually asking when you reach for isNaN or isFinite.
|
|
203
|
-
*
|
|
204
|
-
* IsBounded(42) → true
|
|
205
|
-
* IsBounded(3.14) → true
|
|
206
|
-
* IsBounded(NaN) → false
|
|
207
|
-
* IsBounded(Infinity) → false
|
|
208
|
-
* IsBounded(-Infinity) → false
|
|
209
|
-
* IsBounded('hello') → false
|
|
210
|
-
*/
|
|
211
|
-
export declare function IsBounded(value: unknown): boolean;
|
|
212
225
|
export declare function Eq(a: unknown, b: unknown): boolean;
|
|
213
226
|
/**
|
|
214
227
|
* Honest inequality — what != should have been.
|
|
@@ -350,6 +363,7 @@ export declare function createRuntime(): {
|
|
|
350
363
|
MonadicError: typeof MonadicError;
|
|
351
364
|
typeError: (path: string, expected: string, value: unknown) => MonadicError;
|
|
352
365
|
isMonadicError: typeof isMonadicError;
|
|
366
|
+
bang: (obj: unknown, prop: string) => unknown;
|
|
353
367
|
isError: typeof isError;
|
|
354
368
|
error: (message: string, details?: Partial<Omit<TJSError, "$error" | "message">>) => TJSError;
|
|
355
369
|
composeErrors: typeof composeErrors;
|
|
@@ -361,11 +375,15 @@ export declare function createRuntime(): {
|
|
|
361
375
|
wrapClass: typeof wrapClass;
|
|
362
376
|
compareVersions: typeof compareVersions;
|
|
363
377
|
versionsCompatible: typeof versionsCompatible;
|
|
378
|
+
createRuntime: typeof createRuntime;
|
|
364
379
|
configure: (options: TJSConfig) => void;
|
|
365
380
|
getConfig: () => TJSConfig;
|
|
366
381
|
pushStack: (name: string) => void;
|
|
367
382
|
popStack: () => void;
|
|
368
383
|
getStack: () => string[];
|
|
384
|
+
errors: () => MonadicError[];
|
|
385
|
+
clearErrors: () => MonadicError[];
|
|
386
|
+
getErrorCount: () => number;
|
|
369
387
|
resetRuntime: () => void;
|
|
370
388
|
enterUnsafe: () => void;
|
|
371
389
|
exitUnsafe: () => void;
|
|
@@ -397,7 +415,6 @@ export declare function createRuntime(): {
|
|
|
397
415
|
Eq: typeof Eq;
|
|
398
416
|
NotEq: typeof NotEq;
|
|
399
417
|
TypeOf: typeof TypeOf;
|
|
400
|
-
IsBounded: typeof IsBounded;
|
|
401
418
|
tjsEquals: symbol;
|
|
402
419
|
registerExtension: (typeName: string, methodName: string, fn: (...args: any[]) => any) => void;
|
|
403
420
|
resolveExtension: (value: unknown, methodName: string) => ((...args: any[]) => any) | undefined;
|
|
@@ -431,6 +448,9 @@ export declare const runtime: {
|
|
|
431
448
|
pushStack: typeof pushStack;
|
|
432
449
|
popStack: typeof popStack;
|
|
433
450
|
getStack: typeof getStack;
|
|
451
|
+
errors: typeof errors;
|
|
452
|
+
clearErrors: typeof clearErrors;
|
|
453
|
+
getErrorCount: typeof getErrorCount;
|
|
434
454
|
resetRuntime: typeof resetRuntime;
|
|
435
455
|
enterUnsafe: typeof enterUnsafe;
|
|
436
456
|
exitUnsafe: typeof exitUnsafe;
|
|
@@ -465,7 +485,6 @@ export declare const runtime: {
|
|
|
465
485
|
Eq: typeof Eq;
|
|
466
486
|
NotEq: typeof NotEq;
|
|
467
487
|
TypeOf: typeof TypeOf;
|
|
468
|
-
IsBounded: typeof IsBounded;
|
|
469
488
|
};
|
|
470
489
|
/**
|
|
471
490
|
* Install runtime globally (idempotent, version-checked)
|
package/dist/src/types/Type.d.ts
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* ZipCode.description // '5-digit US zip code'
|
|
17
17
|
*/
|
|
18
18
|
import { type Base } from 'tosijs-schema';
|
|
19
|
+
import { type JSONSchemaObject } from '../lang/json-schema';
|
|
19
20
|
/** JSON Schema object type (simplified) */
|
|
20
21
|
type JSONSchema = {
|
|
21
22
|
type?: string;
|
|
@@ -42,6 +43,10 @@ export interface RuntimeType<T = unknown> {
|
|
|
42
43
|
readonly examples?: T[];
|
|
43
44
|
/** Default value (for instantiation) */
|
|
44
45
|
readonly default?: T;
|
|
46
|
+
/** Generate JSON Schema for this type */
|
|
47
|
+
toJSONSchema(): JSONSchemaObject;
|
|
48
|
+
/** Strip a value down to only the fields matching this type's schema */
|
|
49
|
+
strip(value: unknown): unknown;
|
|
45
50
|
/** Brand for type identification */
|
|
46
51
|
readonly __runtimeType: true;
|
|
47
52
|
}
|
package/dist/tjs-batteries.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
var b=Object.defineProperty;var B=(f)=>f;function I(f,n){this[f]=B.bind(null,n)}var s=(f,n)=>{for(var r in n)b(f,r,{get:n[r],enumerable:!0,configurable:!0,set:I.bind(n,r)})};var U=(f,n)=>()=>(f&&(n=f(f=0)),n);var N=((f)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(f,{get:(n,r)=>(typeof require<"u"?require:n)[r]}):f)(function(f){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+f+'" is not supported')});var J={};s(J,{sep:()=>T,resolve:()=>S,relative:()=>O,posix:()=>W,parse:()=>k,normalize:()=>$,join:()=>H,isAbsolute:()=>G,format:()=>j,extname:()=>V,dirname:()=>y,delimiter:()=>x,default:()=>ff,basename:()=>R,_makeLong:()=>Y});function h(f){if(typeof f!=="string")throw TypeError("Path must be a string. Received "+JSON.stringify(f))}function z(f,n){var r="",u=0,i=-1,t=0,e;for(var g=0;g<=f.length;++g){if(g<f.length)e=f.charCodeAt(g);else if(e===47)break;else e=47;if(e===47){if(i===g-1||t===1);else if(i!==g-1&&t===2){if(r.length<2||u!==2||r.charCodeAt(r.length-1)!==46||r.charCodeAt(r.length-2)!==46){if(r.length>2){var l=r.lastIndexOf("/");if(l!==r.length-1){if(l===-1)r="",u=0;else r=r.slice(0,l),u=r.length-1-r.lastIndexOf("/");i=g,t=0;continue}}else if(r.length===2||r.length===1){r="",u=0,i=g,t=0;continue}}if(n){if(r.length>0)r+="/..";else r="..";u=2}}else{if(r.length>0)r+="/"+f.slice(i+1,g);else r=f.slice(i+1,g);u=g-i-1}i=g,t=0}else if(e===46&&t!==-1)++t;else t=-1}return r}function p(f,n){var r=n.dir||n.root,u=n.base||(n.name||"")+(n.ext||"");if(!r)return u;if(r===n.root)return r+u;return r+f+u}function S(){var f="",n=!1,r;for(var u=arguments.length-1;u>=-1&&!n;u--){var i;if(u>=0)i=arguments[u];else{if(r===void 0)r=process.cwd();i=r}if(h(i),i.length===0)continue;f=i+"/"+f,n=i.charCodeAt(0)===47}if(f=z(f,!n),n)if(f.length>0)return"/"+f;else return"/";else if(f.length>0)return f;else return"."}function $(f){if(h(f),f.length===0)return".";var n=f.charCodeAt(0)===47,r=f.charCodeAt(f.length-1)===47;if(f=z(f,!n),f.length===0&&!n)f=".";if(f.length>0&&r)f+="/";if(n)return"/"+f;return f}function G(f){return h(f),f.length>0&&f.charCodeAt(0)===47}function H(){if(arguments.length===0)return".";var f;for(var n=0;n<arguments.length;++n){var r=arguments[n];if(h(r),r.length>0)if(f===void 0)f=r;else f+="/"+r}if(f===void 0)return".";return $(f)}function O(f,n){if(h(f),h(n),f===n)return"";if(f=S(f),n=S(n),f===n)return"";var r=1;for(;r<f.length;++r)if(f.charCodeAt(r)!==47)break;var u=f.length,i=u-r,t=1;for(;t<n.length;++t)if(n.charCodeAt(t)!==47)break;var e=n.length,g=e-t,l=i<g?i:g,v=-1,L=0;for(;L<=l;++L){if(L===l){if(g>l){if(n.charCodeAt(t+L)===47)return n.slice(t+L+1);else if(L===0)return n.slice(t+L)}else if(i>l){if(f.charCodeAt(r+L)===47)v=L;else if(L===0)v=0}break}var d=f.charCodeAt(r+L),_=n.charCodeAt(t+L);if(d!==_)break;else if(d===47)v=L}var M="";for(L=r+v+1;L<=u;++L)if(L===u||f.charCodeAt(L)===47)if(M.length===0)M+="..";else M+="/..";if(M.length>0)return M+n.slice(t+v);else{if(t+=v,n.charCodeAt(t)===47)++t;return n.slice(t)}}function Y(f){return f}function y(f){if(h(f),f.length===0)return".";var n=f.charCodeAt(0),r=n===47,u=-1,i=!0;for(var t=f.length-1;t>=1;--t)if(n=f.charCodeAt(t),n===47){if(!i){u=t;break}}else i=!1;if(u===-1)return r?"/":".";if(r&&u===1)return"//";return f.slice(0,u)}function R(f,n){if(n!==void 0&&typeof n!=="string")throw TypeError('"ext" argument must be a string');h(f);var r=0,u=-1,i=!0,t;if(n!==void 0&&n.length>0&&n.length<=f.length){if(n.length===f.length&&n===f)return"";var e=n.length-1,g=-1;for(t=f.length-1;t>=0;--t){var l=f.charCodeAt(t);if(l===47){if(!i){r=t+1;break}}else{if(g===-1)i=!1,g=t+1;if(e>=0)if(l===n.charCodeAt(e)){if(--e===-1)u=t}else e=-1,u=g}}if(r===u)u=g;else if(u===-1)u=f.length;return f.slice(r,u)}else{for(t=f.length-1;t>=0;--t)if(f.charCodeAt(t)===47){if(!i){r=t+1;break}}else if(u===-1)i=!1,u=t+1;if(u===-1)return"";return f.slice(r,u)}}function V(f){h(f);var n=-1,r=0,u=-1,i=!0,t=0;for(var e=f.length-1;e>=0;--e){var g=f.charCodeAt(e);if(g===47){if(!i){r=e+1;break}continue}if(u===-1)i=!1,u=e+1;if(g===46){if(n===-1)n=e;else if(t!==1)t=1}else if(n!==-1)t=-1}if(n===-1||u===-1||t===0||t===1&&n===u-1&&n===r+1)return"";return f.slice(n,u)}function j(f){if(f===null||typeof f!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof f);return p("/",f)}function k(f){h(f);var n={root:"",dir:"",base:"",ext:"",name:""};if(f.length===0)return n;var r=f.charCodeAt(0),u=r===47,i;if(u)n.root="/",i=1;else i=0;var t=-1,e=0,g=-1,l=!0,v=f.length-1,L=0;for(;v>=i;--v){if(r=f.charCodeAt(v),r===47){if(!l){e=v+1;break}continue}if(g===-1)l=!1,g=v+1;if(r===46){if(t===-1)t=v;else if(L!==1)L=1}else if(t!==-1)L=-1}if(t===-1||g===-1||L===0||L===1&&t===g-1&&t===e+1){if(g!==-1)if(e===0&&u)n.base=n.name=f.slice(1,g);else n.base=n.name=f.slice(e,g)}else{if(e===0&&u)n.name=f.slice(1,t),n.base=f.slice(1,g);else n.name=f.slice(e,t),n.base=f.slice(e,g);n.ext=f.slice(t,g)}if(e>0)n.dir=f.slice(0,e-1);else if(u)n.dir="/";return n}var T="/",x=":",W,ff;var q=U(()=>{W=((f)=>(f.posix=f,f))({resolve:S,normalize:$,isAbsolute:G,join:H,relative:O,_makeLong:Y,dirname:y,basename:R,extname:V,format:j,parse:k,sep:T,delimiter:x,win32:null,posix:null}),ff=W});var X=new Map,w=new Map;function c(f,n){if(f.length!==n.length)throw Error("Vectors must have the same length for cosine similarity.");let r=0,u=0,i=0;for(let t=0;t<f.length;t++)r+=f[t]*n[t],u+=f[t]*f[t],i+=n[t]*n[t];if(u=Math.sqrt(u),i=Math.sqrt(i),u===0||i===0)return 0;return r/(u*i)}function P(){return{async get(f){return X.get(f)},async set(f,n){X.set(f,n)},async createCollection(f,n,r){if(w.has(f))console.warn(`Collection '${f}' already exists. Overwriting.`);w.set(f,[])},async vectorAdd(f,n){let r=w.get(f);if(!r)throw Error(`Collection '${f}' not found. Create it first.`);if(!n.embedding||!Array.isArray(n.embedding))throw Error("Document must have an 'embedding' property that is an array of numbers.");r.push(n)},async vectorSearch(f,n,r=5){let u=w.get(f);if(!u)throw Error(`Collection '${f}' not found. Create it first.`);let i=u.map((t)=>({doc:t,score:c(n,t.embedding)}));return i.sort((t,e)=>e.score-t.score),i.slice(0,r).map((t)=>t.doc)}}}function a(f){if(typeof f==="string")return{role:"user",content:f};let n=[{type:"text",text:f.text}];for(let r of f.images||[])n.push({type:"image_url",image_url:{url:r}});return{role:"user",content:n}}var m="http://localhost:1234/v1";function Z(f,n=m){return{async predict(r,u,i,t){try{let e=t?f.getStructuredLLM():f.getLLM(),g=[{role:"system",content:r},a(u)],l=await fetch(`${n}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:e.id,messages:g,temperature:0.7,tools:i,response_format:t})});if(!l.ok)throw Error(`LLM Error: ${l.status} ${l.statusText}`);return(await l.json()).choices[0]?.message??{content:""}}catch(e){if(e.cause?.code==="ECONNREFUSED")throw Error("No LLM provider configured. Please start LM Studio or provide an API key.");throw e}},async embed(r){try{let u=f.getEmbedding(),i=await fetch(`${n}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:u.id,input:r})});if(!i.ok)throw Error(`Embedding Error: ${i.status}`);return(await i.json()).data[0]?.embedding??[]}catch(u){if(u.cause?.code==="ECONNREFUSED")throw Error("No LLM provider configured. Please start LM Studio or provide an API key.");throw u}}}}var A=typeof window<"u"&&typeof window.localStorage<"u";async function nf(f){try{if(A){let n=window.localStorage.getItem(".models.cache.json");if(!n)return null;let r=JSON.parse(n);if(r.baseUrl!==f)return null;if(Date.now()-r.timestamp>86400000)return null;return r.models}else{let n=await import("node:fs/promises"),u=(await Promise.resolve().then(() => (q(),J))).join(process.cwd(),".models.cache.json");try{let i=await n.readFile(u,"utf-8"),t=JSON.parse(i);if(t.baseUrl!==f)return null;if(Date.now()-t.timestamp>86400000)return null;return t.models}catch{return null}}}catch(n){return console.warn("⚠️ Error reading model cache:",n),null}}async function rf(f,n){let r={timestamp:Date.now(),baseUrl:f,models:n};try{if(A)window.localStorage.setItem(".models.cache.json",JSON.stringify(r));else{let u=await import("node:fs/promises"),t=(await Promise.resolve().then(() => (q(),J))).join(process.cwd(),".models.cache.json");await u.writeFile(t,JSON.stringify(r,null,2))}}catch(u){console.error("❌ Error writing model cache:",u)}}var C=async(f,n)=>{let r=new AbortController,u=setTimeout(()=>r.abort(),60000);try{let i=await fetch(f,{...n,signal:r.signal});return clearTimeout(u),i}catch(i){throw clearTimeout(u),i}};async function tf(f,n){try{let r={type:"json_schema",json_schema:{name:"test",strict:!1,schema:{type:"object",properties:{status:{type:"string"}}}}},u=await C(`${f}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:n,messages:[{role:"system",content:"You respond in JSON."},{role:"user",content:'Return JSON: {"status": "ok"}'}],response_format:r,max_tokens:20})});if(!u.ok){if(u.status===400)return uf(f,n);return{ok:!1,msg:`HTTP ${u.status}`}}let i=await u.json();return JSON.parse(i.choices[0].message.content),{ok:!0,msg:"OK (Schema)"}}catch(r){return{ok:!1,msg:r.message||"Error"}}}async function uf(f,n){try{if((await C(`${f}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:n,messages:[{role:"user",content:'JSON: {"a":1}'}],response_format:{type:"json_object"},max_tokens:10})})).ok)return{ok:!0,msg:"OK (Legacy Mode)"};return{ok:!1,msg:"Not Supported"}}catch{return{ok:!1,msg:"Legacy Fail"}}}async function ef(f,n){try{return(await C(`${f}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:n,messages:[{role:"user",content:"hi"}],max_tokens:1})})).ok}catch{return!1}}async function gf(f,n){try{let r=await C(`${f}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:n,input:"test"})});if(!r.ok)return null;return(await r.json()).data[0]?.embedding?.length??null}catch{return null}}var Lf="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";async function lf(f,n){try{return(await C(`${f}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:n,messages:[{role:"user",content:[{type:"text",text:"What color is this?"},{type:"image_url",image_url:{url:Lf}}]}],max_tokens:10})})).ok}catch{return!1}}async function F(f){let n=await nf(f),r=[];try{let e=await fetch(`${f}/models`);if(!e.ok)throw Error("Could not connect");r=(await e.json()).data.map((l)=>l.id).sort()}catch(e){if(n)return console.log("⚠️ LM Studio unavailable, using cached model audit."),n;return console.error("❌ Failed to connect to LM Studio."),[]}if(n){let e=n.map((g)=>g.id).sort();if(JSON.stringify(r)===JSON.stringify(e))return console.log("✅ Using cached model audit."),n;console.log("\uD83D\uDD0D Model list changed. Re-running audit...")}console.log("\uD83D\uDD0D Scanning models (this may take a moment)...");let u=[],i=r.map((e)=>({id:e})),t;if(!A)t=await import("node:readline");for(let e of i){if(!A&&t)t.cursorTo(process.stdout,0),process.stdout.write(`\uD83D\uDC49 Testing: ${e.id}...`),t.clearLine(process.stdout,1);let g="Unknown",l=!1,v=!1,L="",d=void 0,_=await ef(f,e.id),M=await gf(f,e.id);if(M)d=M;if(_){g="LLM";let D=await tf(f,e.id);if(l=D.ok,v=await lf(f,e.id),L=l?D.msg:`Fail: ${D.msg}`,v)L+=" +Vision"}else if(M)g="Embedding",L=`OK (Dim: ${M})`;else L="LLM Fail";u.push({id:e.id,type:g,structuredOutput:l,vision:v,dimension:d,status:L})}if(!A&&t)t.cursorTo(process.stdout,0),t.clearLine(process.stdout,0);return console.log(`
|
|
2
|
-
`),console.table(
|
|
3
|
-
|
|
4
|
-
//# debugId=D19E0E009AF3856564756E2164756E21
|
|
1
|
+
var S=new Map,p=new Map;function k(e,t){if(e.length!==t.length)throw new Error("Vectors must have the same length for cosine similarity.");let o=0,n=0,s=0;for(let r=0;r<e.length;r++)o+=e[r]*t[r],n+=e[r]*e[r],s+=t[r]*t[r];return n=Math.sqrt(n),s=Math.sqrt(s),n===0||s===0?0:o/(n*s)}function w(){return{async get(e){return S.get(e)},async set(e,t){S.set(e,t)},async createCollection(e,t,o){p.has(e)&&console.warn(`Collection '${e}' already exists. Overwriting.`),p.set(e,[])},async vectorAdd(e,t){let o=p.get(e);if(!o)throw new Error(`Collection '${e}' not found. Create it first.`);if(!t.embedding||!Array.isArray(t.embedding))throw new Error("Document must have an 'embedding' property that is an array of numbers.");o.push(t)},async vectorSearch(e,t,o=5){let n=p.get(e);if(!n)throw new Error(`Collection '${e}' not found. Create it first.`);let s=n.map(r=>({doc:r,score:k(t,r.embedding)}));return s.sort((r,i)=>i.score-r.score),s.slice(0,o).map(r=>r.doc)}}}function O(e){if(typeof e=="string")return{role:"user",content:e};let t=[{type:"text",text:e.text}];for(let o of e.images||[])t.push({type:"image_url",image_url:{url:o}});return{role:"user",content:t}}var P="http://localhost:1234/v1";function E(e,t=P){return{async predict(o,n,s,r){try{let i=r?e.getStructuredLLM():e.getLLM(),l=[{role:"system",content:o},O(n)],a=await fetch(`${t}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:i.id,messages:l,temperature:.7,tools:s,response_format:r})});if(!a.ok)throw new Error(`LLM Error: ${a.status} ${a.statusText}`);return(await a.json()).choices[0]?.message??{content:""}}catch(i){throw i.cause?.code==="ECONNREFUSED"?new Error("No LLM provider configured. Please start LM Studio or provide an API key."):i}},async embed(o){try{let n=e.getEmbedding(),s=await fetch(`${t}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:n.id,input:o})});if(!s.ok)throw new Error(`Embedding Error: ${s.status}`);return(await s.json()).data[0]?.embedding??[]}catch(n){throw n.cause?.code==="ECONNREFUSED"?new Error("No LLM provider configured. Please start LM Studio or provide an API key."):n}}}}var h=".models.cache.json";var c=typeof window<"u"&&typeof window.localStorage<"u";async function _(e){try{if(c){let t=window.localStorage.getItem(h);if(!t)return null;let o=JSON.parse(t);return o.baseUrl!==e||Date.now()-o.timestamp>864e5?null:o.models}else{let t=await import("node:fs/promises"),n=(await import("node:path")).join(process.cwd(),h);try{let s=await t.readFile(n,"utf-8"),r=JSON.parse(s);return r.baseUrl!==e||Date.now()-r.timestamp>864e5?null:r.models}catch{return null}}}catch(t){return console.warn("\u26A0\uFE0F Error reading model cache:",t),null}}async function N(e,t){let o={timestamp:Date.now(),baseUrl:e,models:t};try{if(c)window.localStorage.setItem(h,JSON.stringify(o));else{let n=await import("node:fs/promises"),r=(await import("node:path")).join(process.cwd(),h);await n.writeFile(r,JSON.stringify(o,null,2))}}catch(n){console.error("\u274C Error writing model cache:",n)}}var u=async(e,t)=>{let o=new AbortController,n=setTimeout(()=>o.abort(),6e4);try{let s=await fetch(e,{...t,signal:o.signal});return clearTimeout(n),s}catch(s){throw clearTimeout(n),s}};async function v(e,t){try{let o={type:"json_schema",json_schema:{name:"test",strict:!1,schema:{type:"object",properties:{status:{type:"string"}}}}},n=await u(`${e}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t,messages:[{role:"system",content:"You respond in JSON."},{role:"user",content:'Return JSON: {"status": "ok"}'}],response_format:o,max_tokens:20})});if(!n.ok)return n.status===400?x(e,t):{ok:!1,msg:`HTTP ${n.status}`};let s=await n.json();return JSON.parse(s.choices[0].message.content),{ok:!0,msg:"OK (Schema)"}}catch(o){return{ok:!1,msg:o.message||"Error"}}}async function x(e,t){try{return(await u(`${e}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t,messages:[{role:"user",content:'JSON: {"a":1}'}],response_format:{type:"json_object"},max_tokens:10})})).ok?{ok:!0,msg:"OK (Legacy Mode)"}:{ok:!1,msg:"Not Supported"}}catch{return{ok:!1,msg:"Legacy Fail"}}}async function D(e,t){try{return(await u(`${e}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t,messages:[{role:"user",content:"hi"}],max_tokens:1})})).ok}catch{return!1}}async function j(e,t){try{let o=await u(`${e}/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t,input:"test"})});return o.ok?(await o.json()).data[0]?.embedding?.length??null:null}catch{return null}}var J="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==";async function $(e,t){try{return(await u(`${e}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t,messages:[{role:"user",content:[{type:"text",text:"What color is this?"},{type:"image_url",image_url:{url:J}}]}],max_tokens:10})})).ok}catch{return!1}}async function A(e){let t=await _(e),o=[];try{let i=await fetch(`${e}/models`);if(!i.ok)throw new Error("Could not connect");o=(await i.json()).data.map(a=>a.id).sort()}catch{return t?(console.log("\u26A0\uFE0F LM Studio unavailable, using cached model audit."),t):(console.error("\u274C Failed to connect to LM Studio."),[])}if(t){let i=t.map(l=>l.id).sort();if(JSON.stringify(o)===JSON.stringify(i))return console.log("\u2705 Using cached model audit."),t;console.log("\u{1F50D} Model list changed. Re-running audit...")}console.log("\u{1F50D} Scanning models (this may take a moment)...");let n=[],s=o.map(i=>({id:i})),r;c||(r=await import("node:readline"));for(let i of s){!c&&r&&(r.cursorTo(process.stdout,0),process.stdout.write(`\u{1F449} Testing: ${i.id}...`),r.clearLine(process.stdout,1));let l="Unknown",a=!1,g=!1,d="",b,T=await D(e,i.id),f=await j(e,i.id);if(f&&(b=f),T){l="LLM";let L=await v(e,i.id);a=L.ok,g=await $(e,i.id),d=a?L.msg:`Fail: ${L.msg}`,g&&(d+=" +Vision")}else f?(l="Embedding",d=`OK (Dim: ${f})`):d="LLM Fail";n.push({id:i.id,type:l,structuredOutput:a,vision:g,dimension:b,status:d})}return!c&&r&&(r.cursorTo(process.stdout,0),r.clearLine(process.stdout,0)),console.log(`
|
|
2
|
+
`),console.table(n),await N(e,n),console.log("\u{1F4DD} Audit results saved to cache."),n}var U="http://localhost:1234/v1",y=class{constructor(t=U){this.baseUrl=t}baseUrl;models=[];defaultLLM=null;defaultEmbedding=null;defaultStructuredLLM=null;async audit(){this.models=await A(this.baseUrl),this.selectDefaults()}selectDefaults(){this.defaultEmbedding=this.models.find(t=>t.type==="Embedding")||null,this.defaultLLM=this.models.find(t=>t.type==="LLM")||null,this.defaultStructuredLLM=this.models.find(t=>t.type==="LLM"&&t.structuredOutput)||null,this.defaultEmbedding||console.warn("\u26A0\uFE0F No embedding model found."),this.defaultLLM||console.warn("\u26A0\uFE0F No LLM found."),this.defaultStructuredLLM||console.warn("\u26A0\uFE0F No LLM with structured output support found.")}getModels(){return this.models}_setDefaultModel(t,o,n,s){let r=this.models.find(i=>i.id===t&&n(i));if(!r)throw new Error(`Model '${t}' not found or is not ${s}.`);this[o]=r}setDefaultLLM(t){this._setDefaultModel(t,"defaultLLM",o=>o.type==="LLM","an LLM")}setDefaultEmbedding(t){this._setDefaultModel(t,"defaultEmbedding",o=>o.dimension!==void 0,"an embedding model")}setDefaultStructuredLLM(t){this._setDefaultModel(t,"defaultStructuredLLM",o=>o.type==="LLM"&&o.structuredOutput,"a structured-output LLM")}getLLM(){if(!this.defaultLLM)throw new Error("No LLM available.");return this.defaultLLM}getEmbedding(){if(!this.defaultEmbedding)throw new Error("No embedding model available.");return this.defaultEmbedding}getStructuredLLM(){if(!this.defaultStructuredLLM)throw new Error("No structured-output LLM available.");return this.defaultStructuredLLM}};var F=typeof window<"u",R=F&&window.location.protocol==="https:",m=null,M=null,C=!1;async function I(){if(C)return{localModels:m,llm:M};if(C=!0,R)return console.log("\u{1F4E1} HTTPS detected - local LLM endpoints disabled. Use HTTP for local LLM support."),{localModels:null,llm:null};try{m=new y,await m.audit(),M=E(m)}catch(e){console.warn("\u26A0\uFE0F Could not connect to local LLM:",e)}return{localModels:m,llm:M}}async function B(){let{localModels:e,llm:t}=await I();return{vector:t?{embed:t.embed}:void 0,store:w(),llmBattery:t,models:e}}async function W(){return B()}var X={store:w(),llmBattery:null,vector:void 0,models:null};export{y as LocalModels,X as batteries,B as getBatteries,E as getLLMCapability,W as getStandardCapabilities,w as getStoreCapabilityDefault};
|
|
3
|
+
//# sourceMappingURL=tjs-batteries.js.map
|