Skip to content

Commit

Permalink
feat: ✨ add JSON5 parsing and stringifying utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
pelikhan committed Dec 22, 2024
1 parent 69a412b commit 482f484
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 1 deletion.
6 changes: 6 additions & 0 deletions packages/core/src/globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { GitClient } from "./git"
import { estimateTokens, truncateTextToTokens } from "./tokens"
import { chunk, resolveTokenEncoder } from "./encoders"
import { runtimeHost } from "./host"
import { JSON5Stringify, JSON5TryParse } from "./json5"

/**
* This file defines global utilities and installs them into the global context.
Expand Down Expand Up @@ -86,6 +87,11 @@ export function installGlobals() {
stringify: JSONLStringify, // Convert objects to JSONL string
})

glb.JSON5 = Object.freeze<JSON5>({
parse: JSON5TryParse,
stringify: JSON5Stringify
})

// Freeze AICI utilities with a generation function
glb.AICI = Object.freeze<AICI>({
gen: (options: AICIGenOptions) => {
Expand Down
16 changes: 15 additions & 1 deletion packages/core/src/types/prompt_template.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2184,6 +2184,20 @@ interface INI {
stringify(value: any): string
}

interface JSON5 {
/**
* Parses a JSON/YAML/XML string to an object
* @param text
*/
parse(text: string | WorkspaceFile): any

/**
* Renders an object to a JSON5-LLM friendly string
* @param value
*/
stringify(value: any): string
}

interface CSVStringifyOptions {
delimiter?: string
header?: boolean
Expand Down Expand Up @@ -2604,7 +2618,7 @@ interface McpServerConfig {

type McpServersConfig = Record<string, Omit<McpServerConfig, "id" | "options">>

type ZodTypeLike = { _def: any, safeParse: any, refine: any }
type ZodTypeLike = { _def: any; safeParse: any; refine: any }

interface ChatGenerationContext extends ChatTurnGenerationContext {
defSchema(
Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/types/prompt_type.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,11 @@ declare var MD: MD
*/
declare var JSONL: JSONL

/**
* JSON5 parsing
*/
declare var JSON5: JSON5

/**
* AICI operations
*/
Expand Down
17 changes: 17 additions & 0 deletions packages/sample/genaisrc/globals.genai.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
script({
tests: {},
model: "small",
})

const data = {
name: "foo",
items: [1, 2, 3],
}

const json5 = JSON5.parse(JSON5.stringify(data))

if (JSON.stringify(json5) !== JSON.stringify(data)) {
throw new Error(
"JSON5.stringify(JSON5.parse(JSON5.stringify(data))) !== data"
)
}

0 comments on commit 482f484

Please sign in to comment.