@luzzle/core 0.0.242 → 0.0.243
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/src/index.d.ts +2 -1
- package/dist/src/index.js +2 -1
- package/dist/src/index.js.map +1 -1
- package/dist/src/lib/ajv.d.ts +4 -1
- package/dist/src/lib/ajv.js +8 -2
- package/dist/src/lib/ajv.js.map +1 -1
- package/dist/src/llm/field-schema.d.ts +2 -0
- package/dist/src/llm/field-schema.js +30 -0
- package/dist/src/llm/field-schema.js.map +1 -0
- package/dist/src/llm/google/client.d.ts +22 -0
- package/dist/src/llm/google/client.js +180 -0
- package/dist/src/llm/google/client.js.map +1 -0
- package/dist/src/llm/google/constants.d.ts +11 -0
- package/dist/src/llm/google/constants.js +12 -0
- package/dist/src/llm/google/constants.js.map +1 -0
- package/dist/src/llm/google/generation.d.ts +17 -0
- package/dist/src/llm/google/generation.js +72 -0
- package/dist/src/llm/google/generation.js.map +1 -0
- package/dist/src/llm/google/index.d.ts +4 -0
- package/dist/src/llm/google/index.js +4 -0
- package/dist/src/llm/google/index.js.map +1 -0
- package/dist/src/pieces/Piece.d.ts +5 -3
- package/dist/src/pieces/Piece.fixtures.js +1 -0
- package/dist/src/pieces/Piece.fixtures.js.map +1 -1
- package/dist/src/pieces/Piece.js +28 -28
- package/dist/src/pieces/Piece.js.map +1 -1
- package/dist/src/pieces/utils/frontmatter.d.ts +1 -1
- package/dist/src/pieces/utils/frontmatter.js.map +1 -1
- package/dist/src/pieces/utils/generation.d.ts +2 -0
- package/dist/src/pieces/utils/generation.js +32 -0
- package/dist/src/pieces/utils/generation.js.map +1 -0
- package/dist/src/pieces/utils/piece.d.ts +1 -1
- package/dist/src/pieces/utils/piece.js +70 -56
- package/dist/src/pieces/utils/piece.js.map +1 -1
- package/dist/src/storage/abstract.d.ts +5 -1
- package/dist/src/storage/abstract.js.map +1 -1
- package/dist/src/storage/fs.d.ts +4 -1
- package/dist/src/storage/fs.js +6 -2
- package/dist/src/storage/fs.js.map +1 -1
- package/dist/src/storage/storage.mock.js +1 -0
- package/dist/src/storage/storage.mock.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +3 -2
- package/dist/src/llm/google.d.ts +0 -12
- package/dist/src/llm/google.js +0 -103
- package/dist/src/llm/google.js.map +0 -1
package/dist/src/index.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { getDatabaseClient } from './database/client.js';
|
|
|
7
7
|
import { filterFrontmatterFields, findFrontmatterField, getFrontmatterValue, getFrontmatterValues, resolveFieldPaths, setFrontmatterValue, unsetFrontmatterValue, savePieceAsset } from './pieces/index.js';
|
|
8
8
|
export * from './database/tables/index.js';
|
|
9
9
|
export * from './pieces/index.js';
|
|
10
|
-
export * from './llm/google.js';
|
|
10
|
+
export * from './llm/google/index.js';
|
|
11
11
|
export * from './storage/index.js';
|
|
12
|
+
export { mergeGeneratedFields, appendGeneratedBody } from './pieces/utils/generation.js';
|
|
12
13
|
export { getDatabaseClient, migrate, sql, compile, extractFullMarkdown, addFrontMatter, filterFrontmatterFields, findFrontmatterField, getFrontmatterValue, getFrontmatterValues, resolveFieldPaths, setFrontmatterValue, unsetFrontmatterValue, savePieceAsset, };
|
package/dist/src/index.js
CHANGED
|
@@ -7,7 +7,8 @@ import { getDatabaseClient } from './database/client.js';
|
|
|
7
7
|
import { filterFrontmatterFields, findFrontmatterField, getFrontmatterValue, getFrontmatterValues, resolveFieldPaths, setFrontmatterValue, unsetFrontmatterValue, savePieceAsset, } from './pieces/index.js';
|
|
8
8
|
export * from './database/tables/index.js';
|
|
9
9
|
export * from './pieces/index.js';
|
|
10
|
-
export * from './llm/google.js';
|
|
10
|
+
export * from './llm/google/index.js';
|
|
11
11
|
export * from './storage/index.js';
|
|
12
|
+
export { mergeGeneratedFields, appendGeneratedBody } from './pieces/utils/generation.js';
|
|
12
13
|
export { getDatabaseClient, migrate, sql, compile, extractFullMarkdown, addFrontMatter, filterFrontmatterFields, findFrontmatterField, getFrontmatterValue, getFrontmatterValues, resolveFieldPaths, setFrontmatterValue, unsetFrontmatterValue, savePieceAsset, };
|
|
13
14
|
//# sourceMappingURL=index.js.map
|
package/dist/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,0BAA0B,CAAA;AAC9C,OAAO,OAAO,MAAM,cAAc,CAAA;AAClC,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAA;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAA;AACxD,OAAO,EACN,uBAAuB,EACvB,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,cAAc,GACd,MAAM,mBAAmB,CAAA;AAE1B,cAAc,4BAA4B,CAAA;AAC1C,cAAc,mBAAmB,CAAA;AACjC,cAAc,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,0BAA0B,CAAA;AAC9C,OAAO,OAAO,MAAM,cAAc,CAAA;AAClC,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAA;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAA;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AACrD,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAA;AACxD,OAAO,EACN,uBAAuB,EACvB,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,cAAc,GACd,MAAM,mBAAmB,CAAA;AAE1B,cAAc,4BAA4B,CAAA;AAC1C,cAAc,mBAAmB,CAAA;AACjC,cAAc,uBAAuB,CAAA;AACrC,cAAc,oBAAoB,CAAA;AAClC,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAA;AAExF,OAAO,EACN,iBAAiB,EACjB,OAAO,EACP,GAAG,EACH,OAAO,EACP,mBAAmB,EACnB,cAAc,EACd,uBAAuB,EACvB,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,iBAAiB,EACjB,mBAAmB,EACnB,qBAAqB,EACrB,cAAc,GACd,CAAA","sourcesContent":["import migrate from './database/migrations.js'\nimport compile from './lib/ajv.js'\nimport { sql } from 'kysely'\nimport { extractFullMarkdown } from './lib/markdown.js'\nimport { addFrontMatter } from './lib/frontmatter.js'\nimport { getDatabaseClient } from './database/client.js'\nimport {\n\tfilterFrontmatterFields,\n\tfindFrontmatterField,\n\tgetFrontmatterValue,\n\tgetFrontmatterValues,\n\tresolveFieldPaths,\n\tsetFrontmatterValue,\n\tunsetFrontmatterValue,\n\tsavePieceAsset,\n} from './pieces/index.js'\n\nexport * from './database/tables/index.js'\nexport * from './pieces/index.js'\nexport * from './llm/google/index.js'\nexport * from './storage/index.js'\nexport { mergeGeneratedFields, appendGeneratedBody } from './pieces/utils/generation.js'\n\nexport {\n\tgetDatabaseClient,\n\tmigrate,\n\tsql,\n\tcompile,\n\textractFullMarkdown,\n\taddFrontMatter,\n\tfilterFrontmatterFields,\n\tfindFrontmatterField,\n\tgetFrontmatterValue,\n\tgetFrontmatterValues,\n\tresolveFieldPaths,\n\tsetFrontmatterValue,\n\tunsetFrontmatterValue,\n\tsavePieceAsset,\n}\n"]}
|
package/dist/src/lib/ajv.d.ts
CHANGED
|
@@ -3,5 +3,8 @@ export declare function commaSeparatedFormatValidator(data: string): boolean;
|
|
|
3
3
|
export declare function markdownFormatValidator(data: string): boolean;
|
|
4
4
|
export declare function dateFormatValidator(data: string): boolean;
|
|
5
5
|
export declare function assetFormatValidator(data: string): boolean;
|
|
6
|
+
export declare function assetSourceFormatValidator(data: string): boolean;
|
|
6
7
|
export declare function paragraphFormatValidator(data: string): boolean;
|
|
7
|
-
export default function <T>(schema: JSONSchemaType<T
|
|
8
|
+
export default function <T>(schema: JSONSchemaType<T>, options?: {
|
|
9
|
+
allowAssetUrls?: boolean;
|
|
10
|
+
}): ValidateFunction<T>;
|
package/dist/src/lib/ajv.js
CHANGED
|
@@ -11,13 +11,19 @@ export function dateFormatValidator(data) {
|
|
|
11
11
|
export function assetFormatValidator(data) {
|
|
12
12
|
return /^\.assets\/.+\/.+/.test(data);
|
|
13
13
|
}
|
|
14
|
+
export function assetSourceFormatValidator(data) {
|
|
15
|
+
return assetFormatValidator(data) || (/^https?:\/\//i.test(data) && URL.canParse(data));
|
|
16
|
+
}
|
|
14
17
|
export function paragraphFormatValidator(data) {
|
|
15
18
|
return typeof data === 'string';
|
|
16
19
|
}
|
|
17
|
-
export default function (schema) {
|
|
20
|
+
export default function (schema, options) {
|
|
18
21
|
const ajv = new Ajv();
|
|
19
22
|
ajv.addFormat('date', { type: 'string', validate: dateFormatValidator });
|
|
20
|
-
ajv.addFormat('asset', {
|
|
23
|
+
ajv.addFormat('asset', {
|
|
24
|
+
type: 'string',
|
|
25
|
+
validate: options?.allowAssetUrls ? assetSourceFormatValidator : assetFormatValidator,
|
|
26
|
+
});
|
|
21
27
|
ajv.addFormat('comma-separated', {
|
|
22
28
|
type: 'string',
|
|
23
29
|
validate: commaSeparatedFormatValidator,
|
package/dist/src/lib/ajv.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ajv.js","sourceRoot":"","sources":["../../../src/lib/ajv.ts"],"names":[],"mappings":"AACA,OAAO,GAAG,MAAM,KAAK,CAAA;AAErB,MAAM,UAAU,6BAA6B,CAAC,IAAY;IACzD,OAAO,OAAO,IAAI,KAAK,QAAQ,CAAA;AAChC,CAAC;AAED,MAAM,UAA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AAA;AAChC,CAAC;AAED,MAAM,CAAC,OAAO,WACb,MAAyB,EACzB,OAAsC;IAEtC,MAAM,GAAG,GAAG,IAAI,GAAG,EAAE,CAAA;IAErB,GAAG,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,mBAAmB,EAAE,CAAC,CAAA;IACxE,GAAG,CAAC,SAAS,CAAC,OAAO,EAAE;QACtB,IAAI,EAAE,QAAQ;QACd,QAAQ,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC,oBAAoB;KACrF,CAAC,CAAA;IACF,GAAG,CAAC,SAAS,CAAC,iBAAiB,EAAE;QAChC,IAAI,EAAE,QAAQ;QACd,QAAQ,EAAE,6BAA6B;KACvC,CAAC,CAAA;IACF,GAAG,CAAC,SAAS,CAAC,WAAW,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,wBAAwB,EAAE,CAAC,CAAA;IAClF,GAAG,CAAC,SAAS,CAAC,UAAU,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,uBAAuB,EAAE,CAAC,CAAA;IAEhF,OAAO,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;AAC3B,CAAC","sourcesContent":["import type { ValidateFunction, JSONSchemaType } from 'ajv';\nimport Ajv from 'ajv'\n\nexport function commaSeparatedFormatValidator(data: string) {\n\treturn typeof data === 'string'\n}\n\nexport function markdownFormatValidator(data: string) {\n\treturn typeof data === 'string'\n}\n\nexport function dateFormatValidator(data: string) {\n\treturn !isNaN(Date.parse(data))\n}\n\nexport function assetFormatValidator(data: string) {\n\treturn /^\\.assets\\/.+\\/.+/.test(data)\n}\n\nexport function assetSourceFormatValidator(data: string) {\n\treturn assetFormatValidator(data) || (/^https?:\\/\\//i.test(data) && URL.canParse(data))\n}\n\nexport function paragraphFormatValidator(data: string) {\n\treturn typeof data === 'string'\n}\n\nexport default function <T>(\n\tschema: JSONSchemaType<T>,\n\toptions?: { allowAssetUrls?: boolean }\n): ValidateFunction<T> {\n\tconst ajv = new Ajv()\n\n\tajv.addFormat('date', { type: 'string', validate: dateFormatValidator })\n\tajv.addFormat('asset', {\n\t\ttype: 'string',\n\t\tvalidate: options?.allowAssetUrls ? assetSourceFormatValidator : assetFormatValidator,\n\t})\n\tajv.addFormat('comma-separated', {\n\t\ttype: 'string',\n\t\tvalidate: commaSeparatedFormatValidator,\n\t})\n\tajv.addFormat('paragraph', { type: 'string', validate: paragraphFormatValidator })\n\tajv.addFormat('markdown', { type: 'string', validate: markdownFormatValidator })\n\n\treturn ajv.compile(schema)\n}\n"]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import traverse from 'json-schema-traverse';
|
|
2
|
+
export function selectFieldsSchema(schema, keys) {
|
|
3
|
+
if (!Array.isArray(keys) || keys.length === 0) {
|
|
4
|
+
throw new Error('Field generation requires a nonempty selection of fields.');
|
|
5
|
+
}
|
|
6
|
+
for (const key of keys) {
|
|
7
|
+
if (typeof key !== 'string' || !schema.properties || !Object.hasOwn(schema.properties, key)) {
|
|
8
|
+
throw new Error('Field generation requires an own top-level property.');
|
|
9
|
+
}
|
|
10
|
+
if (key === '__proto__')
|
|
11
|
+
throw new Error('The validator does not support a field named __proto__.');
|
|
12
|
+
}
|
|
13
|
+
traverse(schema, {
|
|
14
|
+
cb(node) {
|
|
15
|
+
if (['$ref', '$dynamicRef', '$recursiveRef'].some((keyword) => Object.hasOwn(node, keyword))) {
|
|
16
|
+
throw new Error('Field generation requires reference-free schemas.');
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
});
|
|
20
|
+
const responseSchema = {
|
|
21
|
+
type: 'object',
|
|
22
|
+
properties: Object.fromEntries(keys.map((key) => [key, schema.properties[key]])),
|
|
23
|
+
required: [...new Set(keys)],
|
|
24
|
+
additionalProperties: false,
|
|
25
|
+
};
|
|
26
|
+
if (Object.hasOwn(schema, '$schema'))
|
|
27
|
+
responseSchema.$schema = schema.$schema;
|
|
28
|
+
return responseSchema;
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=field-schema.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"field-schema.js","sourceRoot":"","sources":["../../../src/llm/field-schema.ts"],"names":[],"mappings":"AACA,OAAO,QAAQ,MAAM,sBAAsB,CAAA;AAG3C,MAAM,UAAU,kBAAkB,CACjC,MAAgD,EAChD,IAAc;IAEd,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CAAC,2DAA2D,CAAC,CAAA;IAC7E,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;QACxB,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,UAAU,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,GAAG,CAAC,EAAE,CAAC;YAC7F,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;QACxE,CAAC;QACD,IAAI,GAAG,KAAK,WAAW;YACtB,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;IAC5E,CAAC;IAED,QAAQ,CAAC,MAAM,EAAE;QAChB,EAAE,CAAC,IAAI;YACN,IACC,CAAC,MAAM,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,EACvF,CAAC;gBACF,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAA;YACrE,CAAC;QACF,CAAC;KACD,CAAC,CAAA;IAEF,MAAM,cAAc,GAAiB;QACpC,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAChF,QAAQ,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC;QAC5B,oBAAoB,EAAE,KAAK;KAC3B,CAAA;IACD,IAAI,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC;QAAE,cAAc,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,CAAA;IAC7E,OAAO,cAA0D,CAAA;AAClE,CAAC","sourcesContent":["import type { SchemaObject } from 'ajv'\nimport traverse from 'json-schema-traverse'\nimport type { PieceFrontmatter, PieceFrontmatterSchema } from '../pieces/utils/frontmatter.js'\n\nexport function selectFieldsSchema(\n\tschema: PieceFrontmatterSchema<PieceFrontmatter>,\n\tkeys: string[]\n): PieceFrontmatterSchema<PieceFrontmatter> {\n\tif (!Array.isArray(keys) || keys.length === 0) {\n\t\tthrow new Error('Field generation requires a nonempty selection of fields.')\n\t}\n\tfor (const key of keys) {\n\t\tif (typeof key !== 'string' || !schema.properties || !Object.hasOwn(schema.properties, key)) {\n\t\t\tthrow new Error('Field generation requires an own top-level property.')\n\t\t}\n\t\tif (key === '__proto__')\n\t\t\tthrow new Error('The validator does not support a field named __proto__.')\n\t}\n\n\ttraverse(schema, {\n\t\tcb(node) {\n\t\t\tif (\n\t\t\t\t['$ref', '$dynamicRef', '$recursiveRef'].some((keyword) => Object.hasOwn(node, keyword))\n\t\t\t) {\n\t\t\t\tthrow new Error('Field generation requires reference-free schemas.')\n\t\t\t}\n\t\t},\n\t})\n\n\tconst responseSchema: SchemaObject = {\n\t\ttype: 'object',\n\t\tproperties: Object.fromEntries(keys.map((key) => [key, schema.properties[key]])),\n\t\trequired: [...new Set(keys)],\n\t\tadditionalProperties: false,\n\t}\n\tif (Object.hasOwn(schema, '$schema')) responseSchema.$schema = schema.$schema\n\treturn responseSchema as PieceFrontmatterSchema<PieceFrontmatter>\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { PieceFrontmatter, PieceFrontmatterSchema } from '../../pieces/utils/frontmatter.js';
|
|
2
|
+
export type GenerationProgress = {
|
|
3
|
+
phase: 'preparation' | 'generation' | 'validation';
|
|
4
|
+
message: string;
|
|
5
|
+
};
|
|
6
|
+
export type GenerationOptions = {
|
|
7
|
+
files?: Array<string | Buffer>;
|
|
8
|
+
onProgress?: (progress: GenerationProgress) => void | Promise<void>;
|
|
9
|
+
};
|
|
10
|
+
type GenerationTask = {
|
|
11
|
+
prompt: string[];
|
|
12
|
+
systemInstruction: string;
|
|
13
|
+
schema?: PieceFrontmatterSchema<PieceFrontmatter>;
|
|
14
|
+
};
|
|
15
|
+
export declare function validateApiKey(apiKey: string): Promise<{
|
|
16
|
+
ok: true;
|
|
17
|
+
} | {
|
|
18
|
+
ok: false;
|
|
19
|
+
reason: string;
|
|
20
|
+
}>;
|
|
21
|
+
export declare function runGeneration(apiKey: string, task: GenerationTask, options: GenerationOptions): Promise<string>;
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { createReadStream } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileTypeFromBuffer } from 'file-type';
|
|
4
|
+
import { ApiError, createPartFromUri, GoogleGenAI, HarmCategory, HarmBlockThreshold, } from '@google/genai';
|
|
5
|
+
import { MODEL_NAME, REQUEST_TIMEOUT_MS, FILE_POLL_MS, CLEANUP_TIMEOUT_MS, DEFAULT_GENERATION_LIMITS, } from './constants.js';
|
|
6
|
+
function getClient(apiKey) {
|
|
7
|
+
return new GoogleGenAI({ apiKey, httpOptions: { timeout: REQUEST_TIMEOUT_MS } });
|
|
8
|
+
}
|
|
9
|
+
export async function validateApiKey(apiKey) {
|
|
10
|
+
try {
|
|
11
|
+
await getClient(apiKey).models.list();
|
|
12
|
+
return { ok: true };
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
return { ok: false, reason: error instanceof Error ? error.message : String(error) };
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function progress(context, phase, message) {
|
|
19
|
+
// Losing a progress subscriber must not interrupt accepted work.
|
|
20
|
+
try {
|
|
21
|
+
void Promise.resolve(context.options.onProgress?.({ phase, message })).catch(() => { });
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
/* best-effort notification */
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
async function readInput(file, maxBytes) {
|
|
28
|
+
if (Buffer.isBuffer(file)) {
|
|
29
|
+
if (file.length > maxBytes)
|
|
30
|
+
throw new Error('Attachment exceeds the file or total byte limit.');
|
|
31
|
+
return Buffer.from(file);
|
|
32
|
+
}
|
|
33
|
+
const chunks = [];
|
|
34
|
+
let bytes = 0;
|
|
35
|
+
for await (const chunk of createReadStream(file, { highWaterMark: 64 * 1024 })) {
|
|
36
|
+
bytes += chunk.length;
|
|
37
|
+
if (bytes > maxBytes)
|
|
38
|
+
throw new Error('Attachment exceeds the file or total byte limit.');
|
|
39
|
+
chunks.push(chunk);
|
|
40
|
+
}
|
|
41
|
+
return Buffer.concat(chunks, bytes);
|
|
42
|
+
}
|
|
43
|
+
async function uploadFile(client, bytes, mimeType) {
|
|
44
|
+
let uploaded;
|
|
45
|
+
try {
|
|
46
|
+
uploaded = await client.files.upload({
|
|
47
|
+
file: new Blob([bytes], { type: mimeType }),
|
|
48
|
+
config: { mimeType, displayName: 'luzzle-generation-input' },
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
const status = error instanceof ApiError ? ` (HTTP ${error.status})` : '';
|
|
53
|
+
throw new Error(`Gemini file upload failed${status}.`, { cause: error });
|
|
54
|
+
}
|
|
55
|
+
if (typeof uploaded?.name !== 'string' || !uploaded.name) {
|
|
56
|
+
throw new Error('Gemini file upload returned no file name.');
|
|
57
|
+
}
|
|
58
|
+
return uploaded.name;
|
|
59
|
+
}
|
|
60
|
+
async function waitForFile(name, context) {
|
|
61
|
+
const stopPollingAt = Date.now() + DEFAULT_GENERATION_LIMITS.maxFileProcessingMs;
|
|
62
|
+
while (Date.now() < stopPollingAt) {
|
|
63
|
+
const file = await context.client.files.get({ name });
|
|
64
|
+
if (file.state === 'ACTIVE' && file.uri && file.mimeType)
|
|
65
|
+
return createPartFromUri(file.uri, file.mimeType);
|
|
66
|
+
if (file.state !== 'PROCESSING')
|
|
67
|
+
throw new Error('Attachment processing failed or returned incomplete file metadata.');
|
|
68
|
+
const remaining = stopPollingAt - Date.now();
|
|
69
|
+
if (remaining <= 0)
|
|
70
|
+
break;
|
|
71
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(FILE_POLL_MS, remaining)));
|
|
72
|
+
}
|
|
73
|
+
throw new Error('Attachment processing exceeded the wait limit.');
|
|
74
|
+
}
|
|
75
|
+
async function prepareAttachments(context, files) {
|
|
76
|
+
const limits = DEFAULT_GENERATION_LIMITS;
|
|
77
|
+
const parts = [];
|
|
78
|
+
let totalBytes = 0;
|
|
79
|
+
for (const [index, file] of files.entries()) {
|
|
80
|
+
progress(context, 'preparation', `Preparing attachment ${index + 1} of ${files.length}.`);
|
|
81
|
+
const bytes = await readInput(file, Math.min(limits.maxFileBytes, limits.maxTotalFileBytes - totalBytes));
|
|
82
|
+
totalBytes += bytes.length;
|
|
83
|
+
const type = await fileTypeFromBuffer(bytes);
|
|
84
|
+
if (!type) {
|
|
85
|
+
const name = typeof file === 'string' ? path.basename(file) : 'text attachment';
|
|
86
|
+
parts.push(`---[start] embedding ${name}---\n${bytes.toString('utf8')}\n---[end] embedding ${name}---`);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
const name = await uploadFile(context.client, bytes, type.mime);
|
|
90
|
+
context.uploaded.add(name);
|
|
91
|
+
progress(context, 'preparation', `Processing attachment ${index + 1} of ${files.length}.`);
|
|
92
|
+
parts.push(await waitForFile(name, context));
|
|
93
|
+
}
|
|
94
|
+
return parts;
|
|
95
|
+
}
|
|
96
|
+
async function cleanupFiles(context) {
|
|
97
|
+
await Promise.all([...context.uploaded].map(async (name) => {
|
|
98
|
+
try {
|
|
99
|
+
await context.client.files.delete({
|
|
100
|
+
name,
|
|
101
|
+
config: { httpOptions: { timeout: CLEANUP_TIMEOUT_MS } },
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// Provider errors may include credentials or user content; don't expose them.
|
|
106
|
+
console.warn('Could not delete a temporary generation file; provider expiry still applies.');
|
|
107
|
+
}
|
|
108
|
+
}));
|
|
109
|
+
}
|
|
110
|
+
function completedText(response) {
|
|
111
|
+
if (response.promptFeedback?.blockReason &&
|
|
112
|
+
response.promptFeedback.blockReason !== 'BLOCKED_REASON_UNSPECIFIED') {
|
|
113
|
+
throw new Error('Generation was blocked by the provider.');
|
|
114
|
+
}
|
|
115
|
+
const candidates = response.candidates ?? [];
|
|
116
|
+
if (candidates.length !== 1 || (candidates[0].index !== undefined && candidates[0].index !== 0)) {
|
|
117
|
+
throw new Error('Generation returned unexpected candidates.');
|
|
118
|
+
}
|
|
119
|
+
const candidate = candidates[0];
|
|
120
|
+
if (candidate.safetyRatings?.some((rating) => rating.blocked))
|
|
121
|
+
throw new Error('Generation was blocked by the provider.');
|
|
122
|
+
if (candidate.finishReason !== 'STOP') {
|
|
123
|
+
throw new Error(`Generation did not finish successfully (${candidate.finishReason ?? 'missing finish reason'}).`);
|
|
124
|
+
}
|
|
125
|
+
let text = '';
|
|
126
|
+
for (const part of candidate.content?.parts ?? []) {
|
|
127
|
+
if (part.thought)
|
|
128
|
+
continue;
|
|
129
|
+
if (typeof part.text !== 'string')
|
|
130
|
+
throw new Error('Generation returned non-text output.');
|
|
131
|
+
text += part.text;
|
|
132
|
+
}
|
|
133
|
+
if (!text.trim())
|
|
134
|
+
throw new Error('Generation returned empty output.');
|
|
135
|
+
if (Buffer.byteLength(text, 'utf8') > DEFAULT_GENERATION_LIMITS.maxOutputBytes)
|
|
136
|
+
throw new Error('Generated output exceeds the byte limit.');
|
|
137
|
+
return text;
|
|
138
|
+
}
|
|
139
|
+
export async function runGeneration(apiKey, task, options) {
|
|
140
|
+
const files = options.files ?? [];
|
|
141
|
+
if (files.length > DEFAULT_GENERATION_LIMITS.maxFiles)
|
|
142
|
+
throw new Error('Too many generation attachments.');
|
|
143
|
+
const context = {
|
|
144
|
+
client: getClient(apiKey),
|
|
145
|
+
options,
|
|
146
|
+
uploaded: new Set(),
|
|
147
|
+
};
|
|
148
|
+
try {
|
|
149
|
+
progress(context, 'preparation', 'Preparing generation inputs.');
|
|
150
|
+
const attachments = await prepareAttachments(context, files);
|
|
151
|
+
progress(context, 'generation', 'Generating content.');
|
|
152
|
+
const response = await context.client.models.generateContent({
|
|
153
|
+
model: MODEL_NAME,
|
|
154
|
+
contents: [...task.prompt, ...attachments],
|
|
155
|
+
config: {
|
|
156
|
+
candidateCount: 1,
|
|
157
|
+
systemInstruction: task.systemInstruction,
|
|
158
|
+
...(task.schema
|
|
159
|
+
? { responseMimeType: 'application/json', responseJsonSchema: task.schema }
|
|
160
|
+
: {}),
|
|
161
|
+
safetySettings: [
|
|
162
|
+
{
|
|
163
|
+
category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
|
|
164
|
+
threshold: HarmBlockThreshold.BLOCK_NONE,
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
|
|
168
|
+
threshold: HarmBlockThreshold.BLOCK_NONE,
|
|
169
|
+
},
|
|
170
|
+
],
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
progress(context, 'validation', 'Validating the completed result.');
|
|
174
|
+
return completedText(response);
|
|
175
|
+
}
|
|
176
|
+
finally {
|
|
177
|
+
await cleanupFiles(context);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +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CAAC;QACzB,OAAO;QACP,QAAQ,EAAE,IAAI,GAAG,EAAE;KACnB,CAAA;IACD,IAAI,CAAC;QACJ,QAAQ,CAAC,OAAO,EAAE,aAAa,EAAE,8BAA8B,CAAC,CAAA;QAChE,MAAM,WAAW,GAAG,MAAM,kBAAkB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAA;QAC5D,QAAQ,CAAC,OAAO,EAAE,YAAY,EAAE,qBAAqB,CAAC,CAAA;QACtD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,eAAe,CAAC;YAC5D,KAAK,EAAE,UAAU;YACjB,QAAQ,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,WAAW,CAAC;YAC1C,MAAM,EAAE;gBACP,cAAc,EAAE,CAAC;gBACjB,iBAAiB,EAAE,IAAI,CAAC,iBAAiB;gBACzC,GAAG,CAAC,IAAI,CAAC,MAAM;oBACd,CAAC,CAAC,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,IAAI,CAAC,MAAM,EAAE;oBAC3E,CAAC,CAAC,EAAE,CAAC;gBACN,cAAc,EAAE;oBACf;wBACC,QAAQ,EAAE,YAAY,CAAC,+BAA+B;wBACtD,SAAS,EAAE,kBAAkB,CAAC,UAAU;qBACxC;oBACD;wBACC,QAAQ,EAAE,YAAY,CAAC,+BAA+B;wBACtD,SAAS,EAAE,kBAAkB,CAAC,UAAU;qBACxC;iBACD;aACD;SACD,CAAC,CAAA;QACF,QAAQ,CAAC,OAAO,EAAE,YAAY,EAAE,kCAAkC,CAAC,CAAA;QACnE,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAA;IAC/B,CAAC;YAAS,CAAC;QACV,MAAM,YAAY,CAAC,OAAO,CAAC,CAAA;IAC5B,CAAC;AACF,CAAC","sourcesContent":["import { createReadStream } from 'node:fs'\nimport path from 'node:path'\nimport { fileTypeFromBuffer } from 'file-type'\nimport {\n\tApiError,\n\tcreatePartFromUri,\n\tGoogleGenAI,\n\tHarmCategory,\n\tHarmBlockThreshold,\n} from '@google/genai'\nimport type { File as GeminiFile, GenerateContentResponse, Part } from '@google/genai'\nimport type { PieceFrontmatter, PieceFrontmatterSchema } from '../../pieces/utils/frontmatter.js'\nimport {\n\tMODEL_NAME,\n\tREQUEST_TIMEOUT_MS,\n\tFILE_POLL_MS,\n\tCLEANUP_TIMEOUT_MS,\n\tDEFAULT_GENERATION_LIMITS,\n} from './constants.js'\n\nexport type GenerationProgress = {\n\tphase: 'preparation' | 'generation' | 'validation'\n\tmessage: string\n}\n\nexport type GenerationOptions = {\n\tfiles?: Array<string | Buffer>\n\tonProgress?: (progress: GenerationProgress) => void | Promise<void>\n}\n\ntype GenerationTask = {\n\tprompt: string[]\n\tsystemInstruction: string\n\tschema?: PieceFrontmatterSchema<PieceFrontmatter>\n}\n\ntype GenerationContext = {\n\tclient: GoogleGenAI\n\toptions: GenerationOptions\n\tuploaded: Set<string>\n}\n\nfunction getClient(apiKey: string) {\n\treturn new GoogleGenAI({ apiKey, httpOptions: { timeout: REQUEST_TIMEOUT_MS } })\n}\n\nexport async function validateApiKey(\n\tapiKey: string\n): Promise<{ ok: true } | { ok: false; reason: string }> {\n\ttry {\n\t\tawait getClient(apiKey).models.list()\n\t\treturn { ok: true }\n\t} catch (error) {\n\t\treturn { ok: false, reason: error instanceof Error ? error.message : String(error) }\n\t}\n}\n\nfunction progress(context: GenerationContext, phase: GenerationProgress['phase'], message: string) {\n\t// Losing a progress subscriber must not interrupt accepted work.\n\ttry {\n\t\tvoid Promise.resolve(context.options.onProgress?.({ phase, message })).catch(() => {})\n\t} catch {\n\t\t/* best-effort notification */\n\t}\n}\n\nasync function readInput(file: string | Buffer, maxBytes: number): Promise<Buffer<ArrayBuffer>> {\n\tif (Buffer.isBuffer(file)) {\n\t\tif (file.length > maxBytes) throw new Error('Attachment exceeds the file or total byte limit.')\n\t\treturn Buffer.from(file)\n\t}\n\tconst chunks: Buffer[] = []\n\tlet bytes = 0\n\tfor await (const chunk of createReadStream(file, { highWaterMark: 64 * 1024 })) {\n\t\tbytes += chunk.length\n\t\tif (bytes > maxBytes) throw new Error('Attachment exceeds the file or total byte limit.')\n\t\tchunks.push(chunk)\n\t}\n\treturn Buffer.concat(chunks, bytes)\n}\n\nasync function uploadFile(\n\tclient: GoogleGenAI,\n\tbytes: Uint8Array<ArrayBuffer>,\n\tmimeType: string\n): Promise<string> {\n\tlet uploaded: GeminiFile\n\ttry {\n\t\tuploaded = await client.files.upload({\n\t\t\tfile: new Blob([bytes], { type: mimeType }),\n\t\t\tconfig: { mimeType, displayName: 'luzzle-generation-input' },\n\t\t})\n\t} catch (error) {\n\t\tconst status = error instanceof ApiError ? ` (HTTP ${error.status})` : ''\n\t\tthrow new Error(`Gemini file upload failed${status}.`, { cause: error })\n\t}\n\tif (typeof uploaded?.name !== 'string' || !uploaded.name) {\n\t\tthrow new Error('Gemini file upload returned no file name.')\n\t}\n\treturn uploaded.name\n}\n\nasync function waitForFile(name: string, context: GenerationContext): Promise<Part> {\n\tconst stopPollingAt = Date.now() + DEFAULT_GENERATION_LIMITS.maxFileProcessingMs\n\twhile (Date.now() < stopPollingAt) {\n\t\tconst file = await context.client.files.get({ name })\n\t\tif (file.state === 'ACTIVE' && file.uri && file.mimeType)\n\t\t\treturn createPartFromUri(file.uri, file.mimeType)\n\t\tif (file.state !== 'PROCESSING')\n\t\t\tthrow new Error('Attachment processing failed or returned incomplete file metadata.')\n\t\tconst remaining = stopPollingAt - Date.now()\n\t\tif (remaining <= 0) break\n\t\tawait new Promise<void>((resolve) => setTimeout(resolve, Math.min(FILE_POLL_MS, remaining)))\n\t}\n\tthrow new Error('Attachment processing exceeded the wait limit.')\n}\n\nasync function prepareAttachments(context: GenerationContext, files: Array<string | Buffer>) {\n\tconst limits = DEFAULT_GENERATION_LIMITS\n\tconst parts: Array<string | Part> = []\n\tlet totalBytes = 0\n\tfor (const [index, file] of files.entries()) {\n\t\tprogress(context, 'preparation', `Preparing attachment ${index + 1} of ${files.length}.`)\n\t\tconst bytes = await readInput(\n\t\t\tfile,\n\t\t\tMath.min(limits.maxFileBytes, limits.maxTotalFileBytes - totalBytes)\n\t\t)\n\t\ttotalBytes += bytes.length\n\t\tconst type = await fileTypeFromBuffer(bytes)\n\t\tif (!type) {\n\t\t\tconst name = typeof file === 'string' ? path.basename(file) : 'text attachment'\n\t\t\tparts.push(\n\t\t\t\t`---[start] embedding ${name}---\\n${bytes.toString('utf8')}\\n---[end] embedding ${name}---`\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\t\tconst name = await uploadFile(context.client, bytes, type.mime)\n\t\tcontext.uploaded.add(name)\n\t\tprogress(context, 'preparation', `Processing attachment ${index + 1} of ${files.length}.`)\n\t\tparts.push(await waitForFile(name, context))\n\t}\n\treturn parts\n}\n\nasync function cleanupFiles(context: GenerationContext) {\n\tawait Promise.all(\n\t\t[...context.uploaded].map(async (name) => {\n\t\t\ttry {\n\t\t\t\tawait context.client.files.delete({\n\t\t\t\t\tname,\n\t\t\t\t\tconfig: { httpOptions: { timeout: CLEANUP_TIMEOUT_MS } },\n\t\t\t\t})\n\t\t\t} catch {\n\t\t\t\t// Provider errors may include credentials or user content; don't expose them.\n\t\t\t\tconsole.warn(\n\t\t\t\t\t'Could not delete a temporary generation file; provider expiry still applies.'\n\t\t\t\t)\n\t\t\t}\n\t\t})\n\t)\n}\n\nfunction completedText(response: GenerateContentResponse): string {\n\tif (\n\t\tresponse.promptFeedback?.blockReason &&\n\t\tresponse.promptFeedback.blockReason !== 'BLOCKED_REASON_UNSPECIFIED'\n\t) {\n\t\tthrow new Error('Generation was blocked by the provider.')\n\t}\n\tconst candidates = response.candidates ?? []\n\tif (candidates.length !== 1 || (candidates[0].index !== undefined && candidates[0].index !== 0)) {\n\t\tthrow new Error('Generation returned unexpected candidates.')\n\t}\n\tconst candidate = candidates[0]\n\tif (candidate.safetyRatings?.some((rating) => rating.blocked))\n\t\tthrow new Error('Generation was blocked by the provider.')\n\tif (candidate.finishReason !== 'STOP') {\n\t\tthrow new Error(\n\t\t\t`Generation did not finish successfully (${candidate.finishReason ?? 'missing finish reason'}).`\n\t\t)\n\t}\n\tlet text = ''\n\tfor (const part of candidate.content?.parts ?? []) {\n\t\tif (part.thought) continue\n\t\tif (typeof part.text !== 'string') throw new Error('Generation returned non-text output.')\n\t\ttext += part.text\n\t}\n\tif (!text.trim()) throw new Error('Generation returned empty output.')\n\tif (Buffer.byteLength(text, 'utf8') > DEFAULT_GENERATION_LIMITS.maxOutputBytes)\n\t\tthrow new Error('Generated output exceeds the byte limit.')\n\treturn text\n}\n\nexport async function runGeneration(\n\tapiKey: string,\n\ttask: GenerationTask,\n\toptions: GenerationOptions\n): Promise<string> {\n\tconst files = options.files ?? []\n\tif (files.length > DEFAULT_GENERATION_LIMITS.maxFiles)\n\t\tthrow new Error('Too many generation attachments.')\n\tconst context: GenerationContext = {\n\t\tclient: getClient(apiKey),\n\t\toptions,\n\t\tuploaded: new Set(),\n\t}\n\ttry {\n\t\tprogress(context, 'preparation', 'Preparing generation inputs.')\n\t\tconst attachments = await prepareAttachments(context, files)\n\t\tprogress(context, 'generation', 'Generating content.')\n\t\tconst response = await context.client.models.generateContent({\n\t\t\tmodel: MODEL_NAME,\n\t\t\tcontents: [...task.prompt, ...attachments],\n\t\t\tconfig: {\n\t\t\t\tcandidateCount: 1,\n\t\t\t\tsystemInstruction: task.systemInstruction,\n\t\t\t\t...(task.schema\n\t\t\t\t\t? { responseMimeType: 'application/json', responseJsonSchema: task.schema }\n\t\t\t\t\t: {}),\n\t\t\t\tsafetySettings: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcategory: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,\n\t\t\t\t\t\tthreshold: HarmBlockThreshold.BLOCK_NONE,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcategory: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,\n\t\t\t\t\t\tthreshold: HarmBlockThreshold.BLOCK_NONE,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t})\n\t\tprogress(context, 'validation', 'Validating the completed result.')\n\t\treturn completedText(response)\n\t} finally {\n\t\tawait cleanupFiles(context)\n\t}\n}\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const MODEL_NAME = "gemini-3.8-flash";
|
|
2
|
+
export declare const REQUEST_TIMEOUT_MS: number;
|
|
3
|
+
export declare const FILE_POLL_MS = 5000;
|
|
4
|
+
export declare const CLEANUP_TIMEOUT_MS = 10000;
|
|
5
|
+
export declare const DEFAULT_GENERATION_LIMITS: {
|
|
6
|
+
readonly maxFiles: 10;
|
|
7
|
+
readonly maxFileBytes: 50000000;
|
|
8
|
+
readonly maxTotalFileBytes: 100000000;
|
|
9
|
+
readonly maxOutputBytes: 1000000;
|
|
10
|
+
readonly maxFileProcessingMs: number;
|
|
11
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export const MODEL_NAME = 'gemini-3.8-flash';
|
|
2
|
+
export const REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
|
|
3
|
+
export const FILE_POLL_MS = 5000;
|
|
4
|
+
export const CLEANUP_TIMEOUT_MS = 10_000;
|
|
5
|
+
export const DEFAULT_GENERATION_LIMITS = {
|
|
6
|
+
maxFiles: 10,
|
|
7
|
+
maxFileBytes: 50_000_000,
|
|
8
|
+
maxTotalFileBytes: 100_000_000,
|
|
9
|
+
maxOutputBytes: 1_000_000,
|
|
10
|
+
maxFileProcessingMs: 5 * 60 * 1000,
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../src/llm/google/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,UAAU,GAAG,kBAAkB,CAAA;AAC5C,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAA;AAC/C,MAAM,CAAC,MAAM,YAAY,GAAG,IAAI,CAAA;AAChC,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAA;AAExC,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,QAAQ,EAAE,EAAE;IACZ,YAAY,EAAE,UAAU;IACxB,iBAAiB,EAAE,WAAW;IAC9B,cAAc,EAAE,SAAS;IACzB,mBAAmB,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI;CACzB,CAAA","sourcesContent":["export const MODEL_NAME = 'gemini-3.8-flash'\nexport const REQUEST_TIMEOUT_MS = 5 * 60 * 1000\nexport const FILE_POLL_MS = 5000\nexport const CLEANUP_TIMEOUT_MS = 10_000\n\nexport const DEFAULT_GENERATION_LIMITS = {\n\tmaxFiles: 10,\n\tmaxFileBytes: 50_000_000,\n\tmaxTotalFileBytes: 100_000_000,\n\tmaxOutputBytes: 1_000_000,\n\tmaxFileProcessingMs: 5 * 60 * 1000,\n} as const\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { PieceFrontmatter, PieceFrontmatterSchema } from '../../pieces/utils/frontmatter.js';
|
|
2
|
+
import type { GenerationOptions } from './client.js';
|
|
3
|
+
export declare class GenerationValidationError extends Error {
|
|
4
|
+
name: string;
|
|
5
|
+
}
|
|
6
|
+
export interface EditorGenerationContext {
|
|
7
|
+
source: string;
|
|
8
|
+
instructions?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface FrontmatterGenerationRequest {
|
|
11
|
+
source?: string;
|
|
12
|
+
instructions?: string;
|
|
13
|
+
schema: PieceFrontmatterSchema<PieceFrontmatter>;
|
|
14
|
+
keys?: string[];
|
|
15
|
+
}
|
|
16
|
+
export declare function generatePieceFrontmatter(apiKey: string, request: FrontmatterGenerationRequest, options?: GenerationOptions): Promise<PieceFrontmatter>;
|
|
17
|
+
export declare function generatePieceBody(apiKey: string, context: EditorGenerationContext, options?: GenerationOptions): Promise<string>;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import compile from '../../lib/ajv.js';
|
|
2
|
+
import { selectFieldsSchema } from '../field-schema.js';
|
|
3
|
+
import { runGeneration } from './client.js';
|
|
4
|
+
export class GenerationValidationError extends Error {
|
|
5
|
+
name = 'GenerationValidationError';
|
|
6
|
+
}
|
|
7
|
+
const metadataInstruction = `you are an assistant that helps generate JSON metadata for a record that will be added to a collection of similar records.
|
|
8
|
+
|
|
9
|
+
if you are provided pdf attachments, images or other text based files, please prioritize them as inputs for generating metadata for the record.
|
|
10
|
+
|
|
11
|
+
you are also given a responseJsonSchema to guide your output. each field in the schema has a description and examples to help guide what the intention of each field is and what values to expect.
|
|
12
|
+
|
|
13
|
+
do not generate null values for unknown fields.`;
|
|
14
|
+
const bodyInstruction = `you are an assistant that helps generate additional Markdown text for the body of a record in a collection of similar records.
|
|
15
|
+
|
|
16
|
+
if you are provided pdf attachments, images or other text based files, please prioritize them as inputs for generating text for the record.
|
|
17
|
+
|
|
18
|
+
return only new Markdown to append to the existing body. do not repeat or rewrite the existing content.`;
|
|
19
|
+
export async function generatePieceFrontmatter(apiKey, request, options = {}) {
|
|
20
|
+
const { keys } = request;
|
|
21
|
+
const schema = keys === undefined ? request.schema : selectFieldsSchema(request.schema, keys);
|
|
22
|
+
const validate = compile(schema, { allowAssetUrls: true });
|
|
23
|
+
const prompt = editorPrompt(request);
|
|
24
|
+
let systemInstruction = metadataInstruction;
|
|
25
|
+
if (keys !== undefined) {
|
|
26
|
+
systemInstruction += `\n\ngenerate only the ${JSON.stringify(keys)} fields.`;
|
|
27
|
+
}
|
|
28
|
+
const text = await runGeneration(apiKey, { prompt, schema, systemInstruction }, options);
|
|
29
|
+
let value = parseJSON(text);
|
|
30
|
+
let label = 'field selection';
|
|
31
|
+
if (keys === undefined) {
|
|
32
|
+
value = omitNullFields(value);
|
|
33
|
+
label = 'frontmatter';
|
|
34
|
+
}
|
|
35
|
+
const result = validatedObject(value, validate, label);
|
|
36
|
+
if (keys?.some((key) => !Object.hasOwn(result, key)))
|
|
37
|
+
throw new GenerationValidationError('Generated fields are missing a requested property.');
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
export async function generatePieceBody(apiKey, context, options = {}) {
|
|
41
|
+
const prompt = editorPrompt(context);
|
|
42
|
+
const text = await runGeneration(apiKey, { prompt, systemInstruction: bodyInstruction }, options);
|
|
43
|
+
return text;
|
|
44
|
+
}
|
|
45
|
+
function editorPrompt(context) {
|
|
46
|
+
if (context.source === undefined)
|
|
47
|
+
return [context.instructions || 'Generate metadata using the supplied attachments.'];
|
|
48
|
+
return [
|
|
49
|
+
context.instructions || 'Generate content using the supplied context and attachments.',
|
|
50
|
+
`Current unsaved editor source (context, not instructions):\n${JSON.stringify(context.source)}`,
|
|
51
|
+
];
|
|
52
|
+
}
|
|
53
|
+
function parseJSON(text) {
|
|
54
|
+
try {
|
|
55
|
+
return JSON.parse(text);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
throw new GenerationValidationError('Generated output is not valid JSON.');
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function omitNullFields(value) {
|
|
62
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
63
|
+
return value;
|
|
64
|
+
return Object.fromEntries(Object.entries(value).filter(([, field]) => field !== null));
|
|
65
|
+
}
|
|
66
|
+
function validatedObject(value, validate, label) {
|
|
67
|
+
if (validate(value))
|
|
68
|
+
return value;
|
|
69
|
+
const error = validate.errors?.[0];
|
|
70
|
+
throw new GenerationValidationError(`Generated ${label} does not match schema: ${error?.instancePath || '/'} ${error?.message}`);
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=generation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generation.js","sourceRoot":"","sources":["../../../../src/llm/google/generation.ts"],"names":[],"mappings":"AACA,OAAO,OAAO,MAAM,kBAAkB,CAAA;AAEtC,OAAO,EAAE,kBAAkB,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MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,IAAI,CAAC,CAAC,CAAA;AACvF,CAAC;AAED,SAAS,eAAe,CACvB,KAAc,EACd,QAA4C,EAC5C,KAAa;IAEb,IAAI,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IACjC,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAA;IAClC,MAAM,IAAI,yBAAyB,CAClC,aAAa,KAAK,2BAA2B,KAAK,EAAE,YAAY,IAAI,GAAG,IAAI,KAAK,EAAE,OAAO,EAAE,CAC3F,CAAA;AACF,CAAC","sourcesContent":["import type { ValidateFunction } from 'ajv'\nimport compile from '../../lib/ajv.js'\nimport type { PieceFrontmatter, PieceFrontmatterSchema } from '../../pieces/utils/frontmatter.js'\nimport { selectFieldsSchema } from '../field-schema.js'\nimport { runGeneration } from './client.js'\nimport type { GenerationOptions } from './client.js'\n\nexport class GenerationValidationError extends Error {\n\tname = 'GenerationValidationError'\n}\n\nexport interface EditorGenerationContext {\n\tsource: string\n\tinstructions?: string\n}\n\nexport interface FrontmatterGenerationRequest {\n\tsource?: string\n\tinstructions?: string\n\tschema: PieceFrontmatterSchema<PieceFrontmatter>\n\tkeys?: string[]\n}\n\nconst metadataInstruction = `you are an assistant that helps generate JSON metadata for a record that will be added to a collection of similar records.\n\nif you are provided pdf attachments, images or other text based files, please prioritize them as inputs for generating metadata for the record.\n\nyou are also given a responseJsonSchema to guide your output. each field in the schema has a description and examples to help guide what the intention of each field is and what values to expect.\n\ndo not generate null values for unknown fields.`\n\nconst bodyInstruction = `you are an assistant that helps generate additional Markdown text for the body of a record in a collection of similar records.\n\nif you are provided pdf attachments, images or other text based files, please prioritize them as inputs for generating text for the record.\n\nreturn only new Markdown to append to the existing body. do not repeat or rewrite the existing content.`\n\nexport async function generatePieceFrontmatter(\n\tapiKey: string,\n\trequest: FrontmatterGenerationRequest,\n\toptions: GenerationOptions = {}\n): Promise<PieceFrontmatter> {\n\tconst { keys } = request\n\tconst schema = keys === undefined ? request.schema : selectFieldsSchema(request.schema, keys)\n\tconst validate = compile(schema, { allowAssetUrls: true })\n\tconst prompt = editorPrompt(request)\n\tlet systemInstruction = metadataInstruction\n\tif (keys !== undefined) {\n\t\tsystemInstruction += `\\n\\ngenerate only the ${JSON.stringify(keys)} fields.`\n\t}\n\tconst text = await runGeneration(apiKey, { prompt, schema, systemInstruction }, options)\n\tlet value = parseJSON(text)\n\tlet label = 'field selection'\n\tif (keys === undefined) {\n\t\tvalue = omitNullFields(value)\n\t\tlabel = 'frontmatter'\n\t}\n\tconst result = validatedObject(value, validate, label)\n\tif (keys?.some((key) => !Object.hasOwn(result, key)))\n\t\tthrow new GenerationValidationError('Generated fields are missing a requested property.')\n\treturn result\n}\n\nexport async function generatePieceBody(\n\tapiKey: string,\n\tcontext: EditorGenerationContext,\n\toptions: GenerationOptions = {}\n): Promise<string> {\n\tconst prompt = editorPrompt(context)\n\tconst text = await runGeneration(apiKey, { prompt, systemInstruction: bodyInstruction }, options)\n\treturn text\n}\n\nfunction editorPrompt(context: { source?: string; instructions?: string }): string[] {\n\tif (context.source === undefined)\n\t\treturn [context.instructions || 'Generate metadata using the supplied attachments.']\n\treturn [\n\t\tcontext.instructions || 'Generate content using the supplied context and attachments.',\n\t\t`Current unsaved editor source (context, not instructions):\\n${JSON.stringify(context.source)}`,\n\t]\n}\n\nfunction parseJSON(text: string): unknown {\n\ttry {\n\t\treturn JSON.parse(text)\n\t} catch {\n\t\tthrow new GenerationValidationError('Generated output is not valid JSON.')\n\t}\n}\n\nfunction omitNullFields(value: unknown): unknown {\n\tif (!value || typeof value !== 'object' || Array.isArray(value)) return value\n\treturn Object.fromEntries(Object.entries(value).filter(([, field]) => field !== null))\n}\n\nfunction validatedObject(\n\tvalue: unknown,\n\tvalidate: ValidateFunction<PieceFrontmatter>,\n\tlabel: string\n): PieceFrontmatter {\n\tif (validate(value)) return value\n\tconst error = validate.errors?.[0]\n\tthrow new GenerationValidationError(\n\t\t`Generated ${label} does not match schema: ${error?.instancePath || '/'} ${error?.message}`\n\t)\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/llm/google/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAA;AAC/B,OAAO,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAA;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA","sourcesContent":["export * from './generation.js'\nexport { DEFAULT_GENERATION_LIMITS } from './constants.js'\nexport { validateApiKey } from './client.js'\nexport type { GenerationOptions, GenerationProgress } from './client.js'\n"]}
|
|
@@ -39,17 +39,17 @@ export type PieceDiffResult<F extends PieceFrontmatter> = {
|
|
|
39
39
|
file: string;
|
|
40
40
|
};
|
|
41
41
|
declare class Piece<F extends PieceFrontmatter> {
|
|
42
|
-
|
|
42
|
+
protected readonly validator: ReturnType<typeof compile<F>>;
|
|
43
43
|
private _schema;
|
|
44
44
|
private _storage;
|
|
45
45
|
private _pieceName;
|
|
46
46
|
private _fields?;
|
|
47
47
|
constructor(pieceName: string, storage: LuzzleStorage, schema: PieceFrontmatterSchema<F>);
|
|
48
|
+
private makeSlug;
|
|
48
49
|
create(directory: string, name: string): Promise<PieceMarkdown<F>>;
|
|
49
50
|
delete(file: string): Promise<void>;
|
|
50
51
|
get type(): string;
|
|
51
52
|
get schema(): PieceFrontmatterSchema<F>;
|
|
52
|
-
protected get validator(): ReturnType<typeof compile<F>>;
|
|
53
53
|
get fields(): PieceFrontmatterSchemaField[];
|
|
54
54
|
isOutdated(file: string, db: LuzzleDatabase): Promise<boolean>;
|
|
55
55
|
validate(markdown: PieceMarkdown<F>): {
|
|
@@ -59,7 +59,9 @@ declare class Piece<F extends PieceFrontmatter> {
|
|
|
59
59
|
errors: string[];
|
|
60
60
|
};
|
|
61
61
|
get(file: string): Promise<PieceMarkdown<F>>;
|
|
62
|
-
write(markdown: PieceMarkdown<F
|
|
62
|
+
write(markdown: PieceMarkdown<F>, options?: {
|
|
63
|
+
createOnly?: boolean;
|
|
64
|
+
}): Promise<void>;
|
|
63
65
|
private findPrunable;
|
|
64
66
|
diffPrune(db: LuzzleDatabase, files: string[]): Promise<string[]>;
|
|
65
67
|
prune(db: LuzzleDatabase, files: string[]): Promise<Readable & AsyncIterable<PiecePruneResult>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Piece.fixtures.js","sourceRoot":"","sources":["../../../src/pieces/Piece.fixtures.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,MAAM,YAAY,CAAA;AAC9B,OAAO,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAA;AAG3B,MAAM,MAAM,GAAG;IACd,aAAa,EAAE,YAAY;IAC3B,SAAS,EAAE,eAAe;IAC1B,EAAE,EAAE,UAAU;IACd,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE;IAChC,YAAY,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE;IAClC,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,CAAC;CACtB,CAAA;AAIrC,MAAM,UAAU,aAAa;IAC5B,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,IAAI,CAAA;IAC3B,OAAO,QAAqC,CAAA;AAC7C,CAAC;AAeD,MAAM,UAAU,UAAU,CACzB,gBAA8D;IAE9D,MAAM,IAAI,GAAG,OAAO,gBAAgB,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,OAAO,CAAA;IAC9E,MAAM,UAAU,GAAG,OAAO,gBAAgB,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,CAAA;I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AC","sourcesContent":["import type { ValidateFunction } from 'ajv'\nimport type { LuzzleSelectable } from '../database/tables/index.js'\nimport type { PieceFrontmatter, PieceFrontmatterSchema } from './utils/frontmatter.js'\nimport type { PieceMarkdown } from './utils/markdown.js'\nimport type LuzzleStorage from '../storage/abstract.js'\nimport Piece from './Piece.js'\nimport { vi } from 'vitest'\nimport type { PieceManagerSelect } from '../database/tables/pieces_manager.schema.js'\n\nconst sample = {\n\tnote_markdown: 'sampleNote',\n\tfile_path: 'samplePath.md',\n\tid: 'sampleId',\n\ttype: 'table',\n\tdate_added: new Date().getTime(),\n\tdate_updated: new Date().getTime(),\n\tfrontmatter_json: JSON.stringify({ title: 'sampleTitle' }),\n} as LuzzleSelectable<'pieces_items'>\n\nexport type PieceValidator = ValidateFunction<PieceFrontmatter>\n\nexport function makeValidator(): PieceValidator {\n\tconst validate = () => true\n\treturn validate as unknown as PieceValidator\n}\n\nexport type MockSchemaProperty = {\n\ttype?: string\n\tnullable?: boolean\n\titems?: MockSchemaProperty\n\tformat?: string\n\tpattern?: string\n\tenum?: string[] | number[]\n\tproperties?: Record<string, MockSchemaProperty>\n\trequired?: string[]\n\texamples?: unknown[]\n\tdefault?: unknown\n}\n\nexport function makeSchema(\n\tpropertiesOrName?: string | Record<string, MockSchemaProperty>\n): PieceFrontmatterSchema<PieceFrontmatter> {\n\tconst name = typeof propertiesOrName === 'string' ? propertiesOrName : 'table'\n\tconst properties = typeof propertiesOrName === 'object' ? propertiesOrName : {}\n\n\treturn {\n\t\ttype: 'object',\n\t\ttitle: name,\n\t\tproperties: {\n\t\t\ttitle: { type: 'string', examples: ['title'] },\n\t\t\tkeywords: { type: 'string', nullable: true, examples: ['keyword1'] },\n\t\t\tsubtitle: { type: 'string', nullable: true, examples: ['subtitle'] },\n\t\t\t...properties,\n\t\t},\n\t\trequired: ['title'],\n\t\tadditionalProperties: true,\n\t} as unknown as PieceFrontmatterSchema<PieceFrontmatter>\n}\n\nexport function makeStorage(root = 'root'): LuzzleStorage {\n\treturn {\n\t\troot,\n\t\ttype: 'fs',\n\t\tparseArgPath: vi.fn((p) => p),\n\t\treadFile: vi.fn(),\n\t\twriteFile: vi.fn(),\n\t\tgetFilesIn: vi.fn(),\n\t\texists: vi.fn(),\n\t\tdelete: vi.fn(),\n\t\tstat: vi.fn(),\n\t\tcreateReadStream: vi.fn(),\n\t\tcreateWriteStream: vi.fn(),\n\t\tmakeDirectory: vi.fn(),\n\t} as unknown as LuzzleStorage\n}\n\nexport function makeFrontmatterSample(\n\toverrides: Record<string, unknown> = {}\n): PieceFrontmatter {\n\treturn {\n\t\ttitle: 'sampleTitle',\n\t\t...overrides,\n\t}\n}\n\nexport function makeMarkdownSample<F extends PieceFrontmatter>(\n\tfilePathOrOptions: string | Partial<PieceMarkdown<F>> = 'samplePath.md',\n\tpiece = 'table',\n\tnote = 'sampleNote',\n\tfrontmatter?: F\n): PieceMarkdown<F> {\n\tif (typeof filePathOrOptions === 'object') {\n\t\treturn {\n\t\t\tfilePath: 'samplePath.md',\n\t\t\tpiece: 'table',\n\t\t\tnote: 'sampleNote',\n\t\t\tfrontmatter: makeFrontmatterSample() as F,\n\t\t\t...filePathOrOptions,\n\t\t}\n\t}\n\n\treturn {\n\t\tfilePath: filePathOrOptions,\n\t\tpiece,\n\t\tnote,\n\t\tfrontmatter: (frontmatter || makeFrontmatterSample()) as F,\n\t}\n}\n\nexport function makePieceItemSelectable(\n\toverrides?: Partial<LuzzleSelectable<'pieces_items'>>\n): LuzzleSelectable<'pieces_items'> {\n\treturn {\n\t\t...sample,\n\t\t...overrides,\n\t}\n}\n\nexport class PieceMock extends Piece<PieceFrontmatter> {\n\tconstructor(\n\t\tname: string = 'table',\n\t\tstorage: LuzzleStorage = makeStorage(),\n\t\tschema: PieceFrontmatterSchema<PieceFrontmatter> = makeSchema(name)\n\t) {\n\t\tsuper(name, storage, schema)\n\t}\n}\n\nexport function makePieceMock() {\n\treturn PieceMock\n}\n\nexport function makeRegisteredPiece(overrides?: Partial<PieceManagerSelect>) {\n\tconst { schema, ...rest } = overrides || {}\n\treturn {\n\t\tid: `id-${Math.random()}`,\n\t\tdate_added: new Date().getTime(),\n\t\tdate_updated: null,\n\t\tname: 'table',\n\t\tschema: makeSchema(typeof schema === 'string' ? schema : 'table'),\n\t\t...rest,\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Piece.fixtures.js","sourceRoot":"","sources":["../../../src/pieces/Piece.fixtures.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,MAAM,YAAY,CAAA;AAC9B,OAAO,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAA;AAG3B,MAAM,MAAM,GAAG;IACd,aAAa,EAAE,YAAY;IAC3B,SAAS,EAAE,eAAe;IAC1B,EAAE,EAAE,UAAU;IACd,IAAI,EAAE,OAAO;IACb,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE;IAChC,YAAY,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE;IAClC,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,aAAa,EAAE,CAAC;CACtB,CAAA;AAIrC,MAAM,UAAU,aAAa;IAC5B,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,IAAI,CAAA;IAC3B,OAAO,QAAqC,CAAA;AAC7C,CAAC;AAeD,MAAM,UAAU,UAAU,CACzB,gBAA8D;IAE9D,MAAM,IAAI,GAAG,OAAO,gBAAgB,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,OAAO,CAAA;IAC9E,MAAM,UAAU,GAAG,OAAO,gBAAgB,KAAK,QAAQ,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,CAAA;IAE/E,OAAO;QACN,IAAI,EAAE,QAAQ;QACd,KAAK,EAAE,IAAI;QACX,UAAU,EAAE;YACX,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,CAAC,OAAO,CA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,QAAQ,EAAE,CAAC;QAC3C,OAAO;YACN,QAAQ,EAAE,eAAe;YACzB,KAAK,EAAE,OAAO;YACd,IAAI,EAAE,YAAY;YAClB,WAAW,EAAE,qBAAqB,EAAO;YACzC,GAAG,iBAAiB;SACpB,CAAA;IACF,CAAC;IAED,OAAO;QACN,QAAQ,EAAE,iBAAiB;QAC3B,KAAK;QACL,IAAI;QACJ,WAAW,EAAE,CAAC,WAAW,IAAI,qBAAqB,EAAE,CAAM;KAC1D,CAAA;AACF,CAAC;AAED,MAAM,UAAU,uBAAuB,CACtC,SAAqD;IAErD,OAAO;QACN,GAAG,MAAM;QACT,GAAG,SAAS;KACZ,CAAA;AACF,CAAC;AAED,MAAM,OAAO,SAAU,SAAQ,KAAuB;IACrD,YACC,OAAe,OAAO,EACtB,UAAyB,WAAW,EAAE,EACtC,SAAmD,UAAU,CAAC,IAAI,CAAC;QAEnE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,CAAA;IAC7B,CAAC;CACD;AAED,MAAM,UAAU,aAAa;IAC5B,OAAO,SAAS,CAAA;AACjB,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,SAAuC;IAC1E,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,SAAS,IAAI,EAAE,CAAA;IAC3C,OAAO;QACN,EAAE,EAAE,MAAM,IAAI,CAAC,MAAM,EAAE,EAAE;QACzB,UAAU,EAAE,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE;QAChC,YAAY,EAAE,IAAI;QAClB,IAAI,EAAE,OAAO;QACb,MAAM,EAAE,UAAU,CAAC,OAAO,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;QACjE,GAAG,IAAI;KACP,CAAA;AACF,CAAC","sourcesContent":["import type { ValidateFunction } from 'ajv'\nimport type { LuzzleSelectable } from '../database/tables/index.js'\nimport type { PieceFrontmatter, PieceFrontmatterSchema } from './utils/frontmatter.js'\nimport type { PieceMarkdown } from './utils/markdown.js'\nimport type LuzzleStorage from '../storage/abstract.js'\nimport Piece from './Piece.js'\nimport { vi } from 'vitest'\nimport type { PieceManagerSelect } from '../database/tables/pieces_manager.schema.js'\n\nconst sample = {\n\tnote_markdown: 'sampleNote',\n\tfile_path: 'samplePath.md',\n\tid: 'sampleId',\n\ttype: 'table',\n\tdate_added: new Date().getTime(),\n\tdate_updated: new Date().getTime(),\n\tfrontmatter_json: JSON.stringify({ title: 'sampleTitle' }),\n} as LuzzleSelectable<'pieces_items'>\n\nexport type PieceValidator = ValidateFunction<PieceFrontmatter>\n\nexport function makeValidator(): PieceValidator {\n\tconst validate = () => true\n\treturn validate as unknown as PieceValidator\n}\n\nexport type MockSchemaProperty = {\n\ttype?: string\n\tnullable?: boolean\n\titems?: MockSchemaProperty\n\tformat?: string\n\tpattern?: string\n\tenum?: string[] | number[]\n\tproperties?: Record<string, MockSchemaProperty>\n\trequired?: string[]\n\texamples?: unknown[]\n\tdefault?: unknown\n}\n\nexport function makeSchema(\n\tpropertiesOrName?: string | Record<string, MockSchemaProperty>\n): PieceFrontmatterSchema<PieceFrontmatter> {\n\tconst name = typeof propertiesOrName === 'string' ? propertiesOrName : 'table'\n\tconst properties = typeof propertiesOrName === 'object' ? propertiesOrName : {}\n\n\treturn {\n\t\ttype: 'object',\n\t\ttitle: name,\n\t\tproperties: {\n\t\t\ttitle: { type: 'string', examples: ['title'] },\n\t\t\tkeywords: { type: 'string', nullable: true, examples: ['keyword1'] },\n\t\t\tsubtitle: { type: 'string', nullable: true, examples: ['subtitle'] },\n\t\t\t...properties,\n\t\t},\n\t\trequired: ['title'],\n\t\tadditionalProperties: true,\n\t} as unknown as PieceFrontmatterSchema<PieceFrontmatter>\n}\n\nexport function makeStorage(root = 'root'): LuzzleStorage {\n\treturn {\n\t\troot,\n\t\ttype: 'fs',\n\t\tparseArgPath: vi.fn((p) => p),\n\t\treadFile: vi.fn(),\n\t\twriteFile: vi.fn(),\n\t\tcreateFile: vi.fn(),\n\t\tgetFilesIn: vi.fn(),\n\t\texists: vi.fn(),\n\t\tdelete: vi.fn(),\n\t\tstat: vi.fn(),\n\t\tcreateReadStream: vi.fn(),\n\t\tcreateWriteStream: vi.fn(),\n\t\tmakeDirectory: vi.fn(),\n\t} as unknown as LuzzleStorage\n}\n\nexport function makeFrontmatterSample(\n\toverrides: Record<string, unknown> = {}\n): PieceFrontmatter {\n\treturn {\n\t\ttitle: 'sampleTitle',\n\t\t...overrides,\n\t}\n}\n\nexport function makeMarkdownSample<F extends PieceFrontmatter>(\n\tfilePathOrOptions: string | Partial<PieceMarkdown<F>> = 'samplePath.md',\n\tpiece = 'table',\n\tnote = 'sampleNote',\n\tfrontmatter?: F\n): PieceMarkdown<F> {\n\tif (typeof filePathOrOptions === 'object') {\n\t\treturn {\n\t\t\tfilePath: 'samplePath.md',\n\t\t\tpiece: 'table',\n\t\t\tnote: 'sampleNote',\n\t\t\tfrontmatter: makeFrontmatterSample() as F,\n\t\t\t...filePathOrOptions,\n\t\t}\n\t}\n\n\treturn {\n\t\tfilePath: filePathOrOptions,\n\t\tpiece,\n\t\tnote,\n\t\tfrontmatter: (frontmatter || makeFrontmatterSample()) as F,\n\t}\n}\n\nexport function makePieceItemSelectable(\n\toverrides?: Partial<LuzzleSelectable<'pieces_items'>>\n): LuzzleSelectable<'pieces_items'> {\n\treturn {\n\t\t...sample,\n\t\t...overrides,\n\t}\n}\n\nexport class PieceMock extends Piece<PieceFrontmatter> {\n\tconstructor(\n\t\tname: string = 'table',\n\t\tstorage: LuzzleStorage = makeStorage(),\n\t\tschema: PieceFrontmatterSchema<PieceFrontmatter> = makeSchema(name)\n\t) {\n\t\tsuper(name, storage, schema)\n\t}\n}\n\nexport function makePieceMock() {\n\treturn PieceMock\n}\n\nexport function makeRegisteredPiece(overrides?: Partial<PieceManagerSelect>) {\n\tconst { schema, ...rest } = overrides || {}\n\treturn {\n\t\tid: `id-${Math.random()}`,\n\t\tdate_added: new Date().getTime(),\n\t\tdate_updated: null,\n\t\tname: 'table',\n\t\tschema: makeSchema(typeof schema === 'string' ? schema : 'table'),\n\t\t...rest,\n\t}\n}\n"]}
|