Données et stockage
g.store.* — stockage persistant
Section intitulée « g.store.* — stockage persistant »Stockage de documents limité à l’espace de travail, appuyé par LiteDB. Exige un espace de travail ouvert.
| Méthode | Signature | Async | Description |
|---|---|---|---|
put | (collection, key, data) | Non | Stocke un document |
get | (collection, key) → StoreDoc | null | Non | Récupère un document |
list | (collection, options?) → StoreDoc[] | Non | Liste les documents d’une collection |
search | (collection, query, options?) → StoreDoc[] | Non | Recherche textuelle dans une collection |
delete | (collection, key) → boolean | Non | Supprime un document |
count | (collection) → number | Non | Compte les documents |
clear | (collection) | Non | Supprime tous les documents d’une collection |
collections | () → string[] | Non | Liste tous les noms de collections |
StoreDoc :
{ key: string data: any createdAt: string // ISO 8601 updatedAt: string // ISO 8601}StoreListOptions :
{ limit?: number // default: 100 offset?: number // default: 0 sort?: string // "key", "createdAt", "updatedAt" (default) order?: string // "asc" or "desc" (default)}async function main() { // Store data g.store.put("products", "item-1", { name: "Widget", price: 9.99, inStock: true });
// Retrieve it const doc = g.store.get("products", "item-1"); if (doc) g.log("Found: " + doc.data.name);
// Search const results = g.store.search("products", "Widget"); g.log("Matches: " + results.length);}g.queue.* — file de travail
Section intitulée « g.queue.* — file de travail »File persistante limitée à l’espace de travail, avec niveaux de priorité et prise en charge des files des rejets. Exige un espace de travail ouvert.
| Méthode | Signature | Async | Description |
|---|---|---|---|
enqueue | (name, data, options?) | Non | Ajoute un élément à une file |
dequeue | (name) → QueueItem | null | Non | Prend en charge l’élément suivant |
commit | (checkoutId) | Non | Marque un élément dépilé comme terminé |
abort | (checkoutId, error?) → boolean | Non | Renvoie un élément dans la file, ou vers la file des rejets si le maximum de réessais est atteint |
peek | (name) → QueueItem | null | Non | Consulte l’élément suivant sans le prendre en charge |
count | (name) → number | Non | Compte les éléments en attente |
clear | (name) | Non | Supprime tous les éléments d’une file |
list | (name, options?) → QueueItem[] | Non | Liste les éléments en attente |
queues | () → string[] | Non | Liste tous les noms de files |
deadLetter | (name, options?) → DeadLetterItem[] | Non | Liste les éléments de la file des rejets |
retry | (name, deadLetterId) | Non | Remet en file un élément rejeté |
waitForItem | (name, options?) → Promise<QueueItem | null> | Oui | Bloque jusqu’à ce qu’un élément soit disponible |
QueueEnqueueOptions :
{ priority?: number // 0=low, 1=normal (default), 2=high maxRetries?: number // default: 3}QueueItem :
{ id: number data: any priority: number attempts: number maxRetries: number enqueuedAt: string lastAttemptAt?: string lastError?: string}async function main() { // Enqueue work items g.queue.enqueue("urls", { url: "https://example.com/page1" }); g.queue.enqueue("urls", { url: "https://example.com/page2" }, { priority: 2 });
// Process items const item = g.queue.dequeue("urls"); if (!item) return g.log("Queue empty");
await g.nav.navigateToUrl(item.data.url); const html = await g.page.getDom();
// Mark complete g.queue.commit(item.id);}g.search.* — recherche plein texte
Section intitulée « g.search.* — recherche plein texte »Index de recherche Lucene.NET limité à l’espace de travail. Prend en charge les opérateurs booléens, jokers, correspondance approximative et requêtes par champ. Exige un espace de travail ouvert.
| Méthode | Signature | Async | Description |
|---|---|---|---|
index | (fields) | Non | Indexe un document, avec _key et _collection obligatoires |
query | (queryString, options?) → SearchResult[] | Non | Recherche dans l’index avec la syntaxe Lucene |
delete | (collection, key) | Non | Supprime un document de l’index |
deleteByCollection | (collection) → number | Non | Supprime tous les documents d’une collection |
count | (collection?) → number | Non | Compte les documents indexés |
clear | () | Non | Efface tout l’index |
SearchResult :
{ key: string collection: string score: number // Lucene relevance score fields: Record<string, string>}async function main() { // Index documents g.search.index({ _key: "article-1", _collection: "articles", title: "Getting Started with Guida", body: "Guida is a scriptable browser..." });
// Query with Lucene syntax const results = g.search.query("scriptable browser", { collection: "articles" }); for (const r of results) { g.log(r.fields.title + " (score: " + r.score + ")"); }}g.s3.* — stockage d’objets compatible S3
Section intitulée « g.s3.* — stockage d’objets compatible S3 »Stockage compatible S3 via le SDK MinIO. Fonctionne avec AWS S3, MinIO et tout service compatible S3. Le paramètre conn est le nom d’une entrée d’identifiants contenant la chaîne de connexion. Bloqué pour les scripts d’origine MCP.
| Méthode | Signature | Async | Description |
|---|---|---|---|
listBuckets | (conn) → Promise<S3BucketInfo[]> | Oui | Liste tous les buckets accessibles |
bucketExists | (conn, bucket) → Promise<boolean> | Oui | Vérifie si un bucket existe |
listObjects | (conn, bucket, options?) → Promise<S3ObjectInfo[]> | Oui | Liste les objets d’un bucket |
getObjectText | (conn, bucket, key) → Promise<string> | Oui | Télécharge un objet comme texte UTF-8 |
getObject | (conn, bucket, key, localPath) → Promise | Oui | Télécharge un objet vers un fichier local |
putObjectText | (conn, bucket, key, content, contentType?) → Promise | Oui | Téléverse du texte comme objet |
putObject | (conn, bucket, key, localPath, contentType?) → Promise | Oui | Téléverse un fichier local comme objet |
deleteObject | (conn, bucket, key) → Promise | Oui | Supprime un objet |
objectExists | (conn, bucket, key) → Promise<boolean> | Oui | Vérifie si un objet existe |
createBucket | (conn, bucket, region?) → Promise | Oui | Crée un bucket |
copyObject | (conn, srcBucket, srcKey, dstBucket, dstKey) → Promise | Oui | Copie côté serveur, sans transit des données par le client |
getPresignedUrl | (conn, bucket, key, options?) → Promise<string> | Oui | Génère une URL présignée à durée limitée |
S3ListOptions :
{ prefix?: string // filter objects by key prefix maxKeys?: number // max objects to return (default: 1000)}S3BucketInfo :
{ name: string creationDate: string // ISO 8601}S3ObjectInfo :
{ key: string // object key (path) size: number // size in bytes lastModified: string // ISO 8601 etag: string // entity tag (hash)}S3PresignedUrlOptions :
{ method?: string // "GET" (download, default) or "PUT" (upload) expiry?: number // URL expiry in seconds (default: 3600)}async function main() { // List CSV files in a bucket const files = await g.s3.listObjects("my-s3", "data-bucket", { prefix: "exports/" }); g.log("Found " + files.length + " objects");
// Upload scraped data await g.s3.putObjectText( "my-s3", "data-bucket", "exports/results.json", JSON.stringify({ items: [1, 2, 3] }), "application/json" );
// Generate a shareable link const url = await g.s3.getPresignedUrl("my-s3", "data-bucket", "exports/results.json", { expiry: 86400 // 24 hours }); g.log("Download link: " + url);}g.mongodb.* — MongoDB
Section intitulée « g.mongodb.* — MongoDB »Opérations MongoDB via MongoDB.Driver. Le paramètre conn est le nom d’une entrée d’identifiants contenant la chaîne de connexion. Utilise un pool de connexions automatique. Bloqué pour les scripts d’origine MCP.
| Méthode | Signature | Async | Description |
|---|---|---|---|
find | (conn, db, collection, filter?, options?) → Promise<object[]> | Oui | Trouve les documents correspondant à un filtre |
findOne | (conn, db, collection, filter?) → Promise<object | null> | Oui | Trouve le premier document correspondant |
insertOne | (conn, db, collection, document) → Promise<MongoInsertResult> | Oui | Insère un document |
insertMany | (conn, db, collection, documents) → Promise<MongoInsertManyResult> | Oui | Insère plusieurs documents |
updateOne | (conn, db, collection, filter, update) → Promise<MongoUpdateResult> | Oui | Met à jour le premier document correspondant |
updateMany | (conn, db, collection, filter, update) → Promise<MongoUpdateResult> | Oui | Met à jour tous les documents correspondants |
deleteOne | (conn, db, collection, filter) → Promise<MongoDeleteResult> | Oui | Supprime le premier document correspondant |
deleteMany | (conn, db, collection, filter) → Promise<MongoDeleteResult> | Oui | Supprime tous les documents correspondants |
replaceOne | (conn, db, collection, filter, replacement) → Promise<MongoUpdateResult> | Oui | Remplace le premier document correspondant |
countDocuments | (conn, db, collection, filter?) → Promise<number> | Oui | Compte les documents correspondants |
listDatabases | (conn) → Promise<string[]> | Oui | Liste tous les noms de bases |
listCollections | (conn, db) → Promise<string[]> | Oui | Liste les noms de collections d’une base |
aggregate | (conn, db, collection, pipeline) → Promise<object[]> | Oui | Exécute un pipeline d’agrégation |
createIndex | (conn, db, collection, keys, options?) → Promise<string> | Oui | Crée un index et renvoie son nom |
dropCollection | (conn, db, collection) → Promise | Oui | Supprime une collection |
distinct | (conn, db, collection, fieldName, filter?) → Promise<any[]> | Oui | Récupère les valeurs distinctes d’un champ |
bulkWrite | (conn, db, collection, operations) → Promise<MongoBulkWriteResult> | Oui | Exécute plusieurs opérations d’écriture en lot |
MongoFindOptions :
{ sort?: object // e.g., { name: 1, age: -1 } limit?: number skip?: number projection?: object // e.g., { name: 1, _id: 0 }}MongoInsertResult :
{ insertedId: string // the _id of the inserted document}MongoInsertManyResult :
{ insertedCount: number insertedIds: string[]}MongoUpdateResult :
{ matchedCount: number modifiedCount: number}MongoDeleteResult :
{ deletedCount: number}MongoIndexOptions :
{ unique?: boolean // enforce uniqueness name?: string // custom index name}MongoBulkOperation :
{ type: string // "insertOne", "updateOne", "updateMany", // "deleteOne", "deleteMany", "replaceOne" filter?: object // for update/delete/replace document?: object // for insertOne update?: object // for updateOne/updateMany replacement?: object // for replaceOne}MongoBulkWriteResult :
{ insertedCount: number matchedCount: number modifiedCount: number deletedCount: number}async function main() { const conn = "my-mongo"; // nom de l'entrée contenant la chaîne de connexion
// Insert a document const result = await g.mongodb.insertOne(conn, "scraping", "products", { name: "Widget", price: 9.99, category: "tools" }); g.log("Inserted: " + result.insertedId);
// Find with filter and sort const docs = await g.mongodb.find(conn, "scraping", "products", { price: { $lt: 20 } }, { sort: { price: 1 }, limit: 10 } ); g.log("Found " + docs.length + " cheap products");
// Aggregation pipeline const stats = await g.mongodb.aggregate(conn, "scraping", "products", [ { $group: { _id: "$category", avgPrice: { $avg: "$price" }, count: { $sum: 1 } } }, { $sort: { count: -1 } } ]); for (const s of stats) { g.log(s._id + ": " + s.count + " items, avg $" + s.avgPrice.toFixed(2)); }}g.postgres.* — PostgreSQL
Section intitulée « g.postgres.* — PostgreSQL »Opérations PostgreSQL via Npgsql. Utilise les paramètres positionnels $1, $2, etc. : n’interpolez jamais de valeurs dans les chaînes SQL. Le paramètre conn est le nom d’une entrée d’identifiants contenant la chaîne de connexion. Utilise un pool de connexions automatique. Bloqué pour les scripts d’origine MCP.
| Méthode | Signature | Async | Description |
|---|---|---|---|
query | (conn, sql, params?) → Promise<object[]> | Oui | SELECT renvoyant toutes les lignes |
queryOne | (conn, sql, params?) → Promise<object | null> | Oui | SELECT renvoyant la première ligne |
execute | (conn, sql, params?) → Promise<PgExecuteResult> | Oui | INSERT/UPDATE/DELETE |
scalar | (conn, sql, params?) → Promise<any> | Oui | Renvoie la première colonne de la première ligne |
transaction | (conn, callback) → Promise<any> | Oui | Exécute le callback dans une transaction, JavaScript seulement |
executeBatch | (conn, statements) → Promise<PgBatchResult> | Oui | Plusieurs instructions dans une seule transaction |
copyFrom | (conn, table, rows, options?) → Promise<PgCopyResult> | Oui | Insertion en masse via le protocole COPY |
copyTo | (conn, query, options?) → Promise<string[][]> | Oui | Export en masse via le protocole COPY |
listDatabases | (conn) → Promise<string[]> | Oui | Liste les noms de bases non-template |
listSchemas | (conn, options?) → Promise<string[]> | Oui | Liste les noms de schémas |
listTables | (conn, schema?) → Promise<PgTableInfo[]> | Oui | Liste tables et vues avec estimations de lignes |
describeTable | (conn, table, schema?) → Promise<PgColumnInfo[]> | Oui | Métadonnées de colonnes : types, nullabilité, valeurs par défaut, clés primaires |
listIndexes | (conn, table, schema?) → Promise<PgIndexInfo[]> | Oui | Métadonnées d’index avec définitions |
listConstraints | (conn, table, schema?) → Promise<PgConstraintInfo[]> | Oui | Métadonnées de contraintes : PK, FK, UNIQUE, CHECK |
PgExecuteResult :
{ rowsAffected: number}PgTableInfo :
{ name: string schema: string type: string // "table" or "view" estimatedRows: number // from pg_class.reltuples}PgColumnInfo :
{ name: string type: string // e.g., "integer", "character varying", "timestamp with time zone" nullable: boolean defaultValue: string | null isPrimaryKey: boolean maxLength: number | null // for string types}PgIndexInfo :
{ name: string columns: string[] isUnique: boolean isPrimary: boolean definition: string // full CREATE INDEX statement}PgConstraintInfo :
{ name: string type: string // "PRIMARY KEY", "FOREIGN KEY", "UNIQUE", "CHECK" columns: string // comma-separated column names definition: string // constraint definition}PgBatchStatement :
{ sql: string // SQL with $1, $2, ... positional parameters params?: any[] // parameter values}PgBatchResult :
{ results: PgExecuteResult[] // per-statement rowsAffected counts}PgTransactionProxy — passé au callback transaction :
{ query: (sql, params?) => Promise<object[]> queryOne: (sql, params?) => Promise<object | null> execute: (sql, params?) => Promise<PgExecuteResult> scalar: (sql, params?) => Promise<any>}PgCopyFromOptions :
{ columns?: string[] // column names to map row values to (in order) schema?: string // default: "public"}PgCopyToOptions :
{ schema?: string // default: "public" (only for table names, not SQL queries)}PgCopyResult :
{ rowsCopied: number}PgSchemaOptions :
{ includeSystem?: boolean // include pg_* and information_schema (default: false)}async function main() { const conn = "my-postgres"; // nom de l'entrée contenant la chaîne de connexion
try { // Query with parameters const rows = await g.postgres.query(conn, "SELECT id, name, price FROM products WHERE price < $1 ORDER BY price", [20.00] ); g.log("Found " + rows.length + " products");
// Transaction with callback const result = await g.postgres.transaction(conn, async (tx) => { await tx.execute("INSERT INTO orders (product_id, qty) VALUES ($1, $2)", [42, 3]); await tx.execute("UPDATE products SET stock = stock - $1 WHERE id = $2", [3, 42]); return await tx.scalar("SELECT count(*) FROM orders"); }); g.log("Total orders: " + result);
// Bulk insert via COPY (much faster than row-by-row INSERT) const copyResult = await g.postgres.copyFrom(conn, "products", [ ["Widget A", 9.99, 100], ["Widget B", 14.99, 50], ["Widget C", 24.99, 25] ], { columns: ["name", "price", "stock"] }); g.log("Imported " + copyResult.rowsCopied + " rows"); } catch (e) { g.log("Error: " + e.message); }}g.elasticsearch.* — Elasticsearch
Section intitulée « g.elasticsearch.* — Elasticsearch »Prise en charge native de la recherche et de l’indexation dans des clusters Elasticsearch externes avec Elastic.Clients.Elasticsearch. Le paramètre conn est le nom d’une entrée d’identifiants contenant l’objet JSON de connexion : url et éventuellement apiKey ou username/password. Bloqué pour les scripts d’origine MCP.
| Méthode | Signature | Async | Description |
|---|---|---|---|
ping | (conn) → Promise<boolean> | Oui | Vérifie la connexion au cluster et renvoie true en cas de succès |
info | (conn) → Promise<ElasticsearchInfoResult> | Oui | Récupère les métadonnées du cluster : nom, version, tagline, etc. |
createIndex | (conn, indexName, mappingJson?) → Promise<boolean> | Oui | Crée un index avec un mapping JSON facultatif |
deleteIndex | (conn, indexName) → Promise<boolean> | Oui | Supprime un index existant |
index | (conn, indexName, id, document) → Promise<boolean> | Oui | Indexe un objet JS dans le cluster |
get | (conn, indexName, id) → Promise<any> | Oui | Récupère un document par ID et renvoie l’objet _source parsé |
bulk | (conn, indexName, documents, chunkSize?) → Promise<ElasticsearchBulkResult> | Oui | Ingestion à haut débit ; découpe automatiquement les grands tableaux pour éviter les limites de charge utile |
search | (conn, indexName, queryDsl) → Promise<any> | Oui | Exécute une Query DSL JSON brute, chaîne ou objet JS, et renvoie les hits désérialisés |
ElasticsearchInfoResult :
{ name: string clusterName: string clusterUuid: string version: string tagline: string}ElasticsearchBulkResult :
{ total: number successful: number failed: number}async function main() { const conn = "my-elastic"; // nom de l'entrée
// Check connection const isUp = await g.elasticsearch.ping(conn); if (!isUp) return g.log("Connection failed");
// Bulk index documents const docs = [{ id: 1, text: "A" }, { id: 2, text: "B" }]; const bulkRes = await g.elasticsearch.bulk(conn, "products", docs, 1000); g.log(`Indexed ${bulkRes.successful} out of ${bulkRes.total}`);
// Query DSL search const searchRes = await g.elasticsearch.search(conn, "products", { query: { match_all: {} } }); g.log(`Total hits: ${searchRes.hits.total.value}`);}