Funções Embutidas de Nyl

Este documento fornece uma referência abrangente para todas as funções embutidas e módulos disponíveis na linguagem Nyl.

Funções Globais

Function: @dump

  • Signature: fn @dump(bool asJson) any?
  • Description: Exibe o estado atual da VM (locais e globais) para depuração. Retorna JSON se solicitado.

Example:

nyl
@dump() // Dump visual
json = @dump(true) // Dump em JSON

Function: @eval

  • Signature: fn @eval(string script, bool isolated) any?
  • Description: Avalia assincronamente uma string como código Nyl. Retorna uma NylTask que pode ser aguardada com await ou cancelada com .cancel().

Example:

nyl
t = @eval("os.sleep(100); return 1 + 2")
res = await t // 3

Function: @getUILocalLanguage

  • Signature: fn @getUILocalLanguage() string
  • Description: Obtém o idioma de localização atual da UI/Mensagens.

Example:

nyl
lang = @getUILocalLanguage()

Function: @listEmbedded

  • Signature: fn @listEmbedded() list
  • Description: Lista todos os recursos incorporados disponíveis.

Example:

nyl
recursos = @listEmbedded()

Function: @loadEmbedded

  • Signature: fn @loadEmbedded(string path, bool asText) any?
  • Description: Carrega um recurso incorporado como uma string.

Example:

nyl
conteudo = @loadEmbedded("nome_do_recurso")

Function: @printBrand

  • Signature: fn @printBrand() void
  • Description: Imprime as informações de marca/versão do Nyl no console.

Example:

nyl
@printBrand()

Function: @setUILocalLanguage

  • Signature: fn @setUILocalLanguage(string culture) bool
  • Description: Define o idioma de localização para UI/Mensagens.

Example:

nyl
@setUILocalLanguage("pt-BR")

Function: add

  • Signature: fn add(map obj, string name, any value) bool

Function: compareVersions

  • Signature: fn compareVersions(string targetSemVerToCompare, string currentSemVer) number
  • Description: Compara duas versões semânticas. Retorna 0 se forem iguais, 1 se o alvo for mais recente, -1 se for mais antiga.

Function: concatStr

  • Signature: fn concatStr(list values) string
  • Description: Concatena uma lista de valores em uma única string.

Function: contains

  • Signature: fn contains(string str, string value, bool caseSenitive) bool
  • Description: Verifica se uma string contém outra substring.

Function: countdownTimeStr

  • Signature: fn countdownTimeStr(datetime initDate) string
  • Description: Calcula o tempo restante até uma data de destino.

Function: createDate

  • Signature: fn createDate(number year, number month, number day, number hour, number minute, number second) datetime
  • Description: Cria um novo objeto DateTime.

Function: cutStr

  • Signature: fn cutStr(string str, number counter, bool withEllipsis) string
  • Description: Abrevia uma string longa com reticências.

Function: endsWith

  • Signature: fn endsWith(string str, string value, bool caseSenitive) bool
  • Description: Verifica se uma string termina com o valor especificado.

Function: endWithAnyStr

  • Signature: fn endWithAnyStr(string str, list values) bool
  • Description: Verifica se uma string termina com qualquer um dos valores de uma lista.

Function: filter

  • Signature: fn filter(list array, fn predicate) []any
  • Description: Filtra um array usando uma função de callback de predicado

Example:

nyl
numeros = [1, 2, 3, 4, 5]
pares = filter(numeros, fn(x) => x % 2 == 0)
println(pares) // [2, 4]

Function: findWithRegex

  • Signature: fn findWithRegex(string input, string pattern) list
  • Description: Localiza todas as ocorrências de um padrão regex e retorna os grupos correspondentes.

Function: fingerPrintId

  • Signature: fn fingerPrintId(bool includeProcessId) (string fullhash, string shorthash)
  • Description: Gera uma ID de impressão digital exclusiva para a máquina baseada em informações de hardware e sistema.

Example:

nyl
fingerPrintId()
// >[
//    "69c040757cf148367bbfe5046ec4453fa5691f817788b3251ec69e7e9584f057", // fullhash
//    "79c540757cf74836" // shorthash
//  ]
fingerPrintId().shorthash // ou fingerPrintId()[0]
// > "79c540757cf74836"

Function: fnExists

  • Signature: fn fnExists(string fnName) bool
  • Description: Verifica se uma função com o nome especificado existe no escopo global.

Example:

nyl
if fnExists("minhaFunc") {
    minhaFunc()
}

Function: formatFileLength

  • Signature: fn formatFileLength(string str) string
  • Description: Formata uma contagem de bytes em um tamanho de arquivo legível (KB, MB, GB...).

Function: formatStr

  • Signature: fn formatStr(string str, list values) string
  • Description: Formata uma string usando substituição de marcadores.

Function: formatTime

  • Signature: fn formatTime(number value, bool isSeconds, bool ignoreEmptyValues) string
  • Description: Formata um valor de milissegundos em uma duração legível.

Function: formatToStr

  • Signature: fn formatToStr(any obj, string keyValueDelimiter, bool setNameInCamelCase, string camelCaseDelimiter, bool useNegriteAndItalicToKeyValue) string
  • Description: Formata um objeto complexo (Instância, Mapa) em uma string legível.

Function: free

  • Signature: fn free(any value) bool
  • Description: Aciona manualmente o descarte de recursos ou remove um objeto da memória.

Example:

nyl
obj = os.newTerminal()
free(obj)

Function: freeAll

  • Signature: fn freeAll() bool
  • Description: Limpa todos os globais que não são do sistema e aciona uma coleta de lixo.

Example:

nyl
freeAll()

Function: fromBase64

  • Signature: fn fromBase64(string str) string
  • Description: Decodifica uma string Base64 de volta para texto simples.

Function: genGuidV4

  • Signature: fn genGuidV4(bool onlyNumbers, string? format) string
  • Description: Gera um GUID aleatório (Versão 4).

Example:

nyl
id = genGuidV4()

Function: genGuidV7

  • Signature: fn genGuidV7(bool onlyNumbers, string? format) string
  • Description: Gera um GUID ordenado por tempo (Versão 7).

Example:

nyl
id = genGuidV7()

Function: genToken

  • Signature: fn genToken() void
  • Description: Gera um token de segurança baseado nas entradas de nome de usuário e chave de acesso.

Example:

nyl
# Comando interativo para gerar chaves
genToken()

Function: getFileMD5Checksum

  • Signature: fn getFileMD5Checksum(string filePath) string
  • Description: Calcula o checksum MD5 de um arquivo.

Example:

nyl
md5 = os.getFileMD5Checksum("app.exe")

Function: getFileSHA1Checksum

  • Signature: fn getFileSHA1Checksum(string filePath) string
  • Description: Calcula o checksum SHA1 de um arquivo.

Example:

nyl
sha1 = os.getFileSHA1Checksum("app.exe")

Function: getFileSHA256Checksum

  • Signature: fn getFileSHA256Checksum(string filePath) string
  • Description: Calcula o checksum SHA256 de um arquivo.

Example:

nyl
sha256 = os.getFileSHA256Checksum("app.exe")

Function: getFileSHA512Checksum

  • Signature: fn getFileSHA512Checksum(string filePath) string
  • Description: Calcula o checksum SHA512 de um arquivo.

Example:

nyl
sha512 = os.getFileSHA512Checksum("app.exe")

Function: getLoggerLocation

  • Signature: fn getLoggerLocation() (string File, string Location)

Function: getTime

  • Signature: fn getTime() datetime
  • Description: Obtém a hora local atual do sistema.

Function: getTimeUtc

  • Signature: fn getTimeUtc() datetime
  • Description: Obtém a hora UTC atual.

Function: getTimeZones

  • Signature: fn getTimeZones() list
  • Description: Retorna uma lista de todos os IDs de fuso horário do sistema disponíveis.

Function: getTimeZoneUtc

  • Signature: fn getTimeZoneUtc(string zoneId) datetime
  • Description: Obtém a hora atual ajustada para um fuso horário específico.

Function: hashMD5

  • Signature: fn hashMD5(string str) string
  • Description: Gera um hash MD5 da string.

Function: hashOf

  • Signature: fn hashOf(any value) number
  • Description: Retorna um código de hash profundo para o valor fornecido.

Example:

nyl
h = hashOf([1, 2, 3])

Function: hashSHA256

  • Signature: fn hashSHA256(string str) string
  • Description: Gera um hash SHA256 da string.

Function: indexOf

  • Signature: fn indexOf(string str, string value, bool caseSenitive) number
  • Description: Retorna o índice da primeira ocorrência de uma substring.

Function: input

  • Signature: fn input(string label, string cursor) any?
  • Description: Lê uma entrada do console com um rótulo e cursor opcionais.

Example:

nyl
nome = input("Digite seu nome", ":")
println("Olá {nome}!")

Function: isCurrentVersion

  • Signature: fn isCurrentVersion(string targetSemVerToCompare, string currentSemVer) bool
  • Description: Verifica se a versão de destino é igual à versão atual.

Function: isNextVersion

  • Signature: fn isNextVersion(string nextSemVerToCompare, string currentSemVer) bool
  • Description: Verifica se a versão de destino é uma versão mais recente que a atual.

Function: isNilOrEmpty

  • Signature: fn isNilOrEmpty(string? str) bool
  • Description: Verifica se uma string é nula ou vazia.

Function: isNilOrWhiteSpace

  • Signature: fn isNilOrWhiteSpace(string? value) bool
  • Description: Verifica se uma string é nula, vazia ou apenas espaço em branco.

Function: isPreviousVersion

  • Signature: fn isPreviousVersion(string previousSemVerToCompare, string currentSemVer) bool
  • Description: Verifica se a versão de destino é uma versão mais antiga que a atual.

Function: isValidUriScheme

  • Signature: fn isValidUriScheme(string str) bool
  • Description: Verifica se uma string representa um esquema de URI/URL válido.

Function: joinstr

  • Signature: fn joinstr(string? separator, any values) string
  • Description: Une elementos de uma lista ou mapa em uma única string usando um separador.

Function: len

  • Signature: fn len(any? value) number
  • Description: Retorna o comprimento de uma string, array ou mapa.

Example:

nyl
l1 = len("abc") // 3
l2 = len([1, 2]) // 2

Function: logerr

  • Signature: fn logerr(string message, bool printOnConsole) void
  • Description: Registra uma mensagem de erro no logger atual.

Example:

nyl
logerr("Ocorreu um erro!")

Function: loggerInfo

  • Signature: fn loggerInfo() map
  • Description: Obtém informações sobre a configuração atual do logger.

Example:

nyl
info = loggerInfo()
println(info.location)

Function: loginfo

  • Signature: fn loginfo(string message, bool printOnConsole) void
  • Description: Registra uma mensagem de informação no logger atual.

Example:

nyl
loginfo("Iniciando processo...")

Function: logwarn

  • Signature: fn logwarn(string message, bool printOnConsole) void
  • Description: Registra uma mensagem de aviso no logger atual.

Example:

nyl
logwarn("O uso de recursos está alto.")

Function: map

  • Signature: fn map(list array, fn callback) []any
  • Description: Mapeia um array através de uma função de callback e retorna uma nova lista

Example:

nyl
numeros = [1, 2, 3, 4]
dobrados = map(numeros, fn(x) => x * 2)
println(dobrados) // [2, 4, 6, 8]

Function: nameOf

  • Signature: fn nameOf(any value) string
  • Description: Retorna o nome de uma variável, função ou tipo.

Example:

nyl
x = 10
println(nameOf(x)) // "x"

Function: openLogger

  • Signature: fn openLogger() void
  • Description: Abre a pasta de logs atual no explorador de arquivos.

Example:

nyl
openLogger()

Function: parse

  • Signature: fn parse(any targetType, any value) any?
  • Description: Analisa um valor para um tipo de destino especificado.

Example:

nyl
val = parse("int", "123")

Function: pause

  • Signature: fn pause(bool returnKey) any?
  • Description: Pausa a execução até que uma tecla seja pressionada. Opcionalmente retorna a tecla pressionada.

Example:

nyl
println("Pressione qualquer tecla para continuar...")
pause()

Function: pid

  • Signature: fn pid(Process process) number
  • Description: Retorna o ID do Processo (PID) do objeto Process fornecido.

Example:

nyl
id = proc.pid()

Function: pKill

  • Signature: fn pKill(Process process, bool killChilds) void
  • Description: Encerra o objeto Process fornecido.

Example:

nyl
proc.pKill()

Function: pName

  • Signature: fn pName(Process process) string
  • Description: Retorna o nome do objeto Process fornecido.

Example:

nyl
nome = proc.pName()

Function: print

  • Signature: fn print(any? input) void
  • Description: Imprime um valor no console

Example:

nyl
print("Olá ")
print("Mundo")

Function: println

  • Signature: fn println(any? input) void
  • Description: Imprime um valor no console com uma nova linha

Example:

nyl
println("Olá Mundo")
println(123)

Function: psTable

  • Signature: fn psTable(list processInfos) void
  • Description: Exibe uma lista de processos em uma tabela formatada no console.

Example:

nyl
os.getProcesses().psTable()

Function: pWrite

  • Signature: fn pWrite(Process process, string message) void
  • Description: Grava uma mensagem na entrada padrão do objeto Process fornecido.

Example:

nyl
proc.pWrite("exit
")

Function: random

  • Signature: fn random(number min, number max) number

Function: randomStr

  • Signature: fn randomStr(string alphalet, number size) string
  • Description: Gera uma string aleatória criptograficamente forte.

Function: repeat

  • Signature: fn repeat(number count, fn callback) void
  • Description: Repete uma função de callback N vezes

Example:

nyl
repeat(3, fn(i) {
    println("Iteração: {i}")
})

Function: replace

  • Signature: fn replace(string? str, string oldStr, string newStr) string
  • Description: Substitui todas as ocorrências de uma substring por outra.

Function: replaceWithRegex

  • Signature: fn replaceWithRegex(string input, string pattern, map replacements) string
  • Description: Substitui substrings que correspondem a um padrão regex usando um mapa de substituição.

Function: reverse

  • Signature: fn reverse(string str) string
  • Description: Inverte os caracteres de uma string.

Function: setLoggerLocation

  • Signature: fn setLoggerLocation(string locationInAppdataPath, string fileNameExt) void

Function: split

  • Signature: fn split(string? str, string separator) []string
  • Description: Divide uma string em um array de substrings com base em um separador.

Function: startsWith

  • Signature: fn startsWith(string str, string value, bool caseSenitive) bool
  • Description: Verifica se uma string começa com o valor especificado.

Function: startTime

  • Signature: fn startTime() Stopwatch
  • Description: Inicia um cronômetro de alta precisão.

Function: startWithAnyStr

  • Signature: fn startWithAnyStr(string str, list values) bool
  • Description: Verifica se uma string começa com qualquer um dos valores de uma lista.

Function: stopTime

  • Signature: fn stopTime(Stopwatch sw, bool inSeconds, bool formatted) string
  • Description: Para o cronômetro e retorna o tempo decorrido.

Function: substr

  • Signature: fn substr(string? str, number startIndex, number length) string
  • Description: Retorna uma parte da string (substring).

Function: toBase64

  • Signature: fn toBase64(string str) string
  • Description: Codifica uma string em Base64.

Function: toBytes

  • Signature: fn toBytes(string str) []byte
  • Description: Codifica uma string em um array de bytes.

Function: toCamelCase

  • Signature: fn toCamelCase(string str, string delimiter) string
  • Description: Converte uma string delimitada em CamelCase.

Function: toLower

  • Signature: fn toLower(string? str) string
  • Description: Converte a string para minúsculas.

Function: toStr

  • Signature: fn toStr(any bytes, bool removeTrailingNilChars) string
  • Description: Decodifica um array de bytes ou lista de bytes em uma string.

Function: toString

  • Signature: fn toString(any value, string? formatter) string
  • Description: Converte um valor em sua representação de string com formatação opcional.

Function: toUpper

  • Signature: fn toUpper(string? str) string
  • Description: Converte a string para maiúsculas.

Function: trim

  • Signature: fn trim(string? str) string
  • Description: Remove espaços em branco no início e no fim.

Function: typeOf

  • Signature: fn typeOf(any value) string
  • Description: Retorna o nome do tipo do valor fornecido.

Example:

nyl
println(typeOf(123)) // "int"
println(typeOf("abc")) // "string"

Módulos

Module: array

Function: array.clear

  • Signature: fn clear(list list) void
  • Description: Limpa todos os itens da lista

Function: array.indexOf

  • Signature: fn indexOf(list list, any item, bool caseSensitive) number
  • Description: Obtém o índice do item na lista

Function: array.insert

  • Signature: fn insert(list list, number index, any value) list
  • Description: Insere um item em um índice específico na lista

Function: array.join

  • Signature: fn join(list arrayList, string separator) string
  • Description: Junta os itens da lista em uma string com separador

Function: array.len

  • Signature: fn len(list list) number
  • Description: Obtém o comprimento da lista

Function: array.pop

  • Signature: fn pop(list list) any?
  • Description: Remove o último item da lista

Function: array.push

  • Signature: fn push(list list, any value) list
  • Description: Adiciona um novo item à lista

Function: array.remove

  • Signature: fn remove(list list, any item, bool caseSensitive) bool
  • Description: Remove um item da lista

Function: array.removeAt

  • Signature: fn removeAt(list list, number index) any?
  • Description: Remove um item em um índice específico na lista

Function: array.reverse

  • Signature: fn reverse(list arrayList) list
  • Description: Inverte a lista

Function: array.sort

  • Signature: fn sort(list arrayList) list
  • Description: Ordena a lista em ordem crescente

Function: array.sortDescending

  • Signature: fn sortDescending(list arrayList) list
  • Description: Ordena a lista em ordem decrescente

Module: auth

Function: auth.addOrUpdateUser

  • Signature: fn addOrUpdateUser(NylServer server, string username, string passwordOrToken, string role, bool isToken) bool
  • Description: Adiciona ou atualiza um usuário na loja de autenticação

Function: auth.addUser

  • Signature: fn addUser(NylServer server, string username, string passwordOrToken, string role, bool isToken, bool forceReplace) bool
  • Description: Registra um usuário na loja de autenticação

Function: auth.approve

  • Signature: fn approve(NylServer server, map credentials, string redirectUrl) NylTuple
  • Description: Valida credenciais e gera token de sessão

Function: auth.deny

  • Signature: fn deny(string message) NylTuple
  • Description: Retorna JSON de falha de autenticação

Function: auth.removeUser

  • Signature: fn removeUser(NylServer server, string username) bool
  • Description: Remove um usuário da loja de autenticação

Function: auth.updateUser

  • Signature: fn updateUser(NylServer server, string username, string passwordOrToken, string? role, bool isToken) bool
  • Description: Atualiza as credenciais de um usuário existente

Module: byte

Function: byte.parse

  • Signature: fn parse(any value) any?
  • Description: Analisa um valor para um byte (0-255).

Example:

nyl
b = byte.parse("255")

Module: datetime

Function: datetime.parse

  • Signature: fn parse(any value) any?
  • Description: Analisa uma string para um objeto DateTime.

Example:

nyl
dt = datetime.parse("2026-04-10")

Module: decimal

Function: decimal.parse

  • Signature: fn parse(any value) any?
  • Description: Analisa uma string para um número decimal de alta precisão.

Example:

nyl
d = decimal.parse("123.456789")

Module: float

Function: float.parse

  • Signature: fn parse(any value) any?
  • Description: Analisa uma string para um número de ponto flutuante.

Example:

nyl
n = number.parse("123.45")

Module: html

Function: html.a

  • Signature: fn a(string href) HtmlNode
  • Description: Cria um elemento <a> (link).

Function: html.addClass

  • Signature: fn addClass(HtmlNode htmlNode, string className) HtmlNode
  • Description: Adiciona uma classe CSS a um elemento HTML.

Function: html.addClasses

  • Signature: fn addClasses(HtmlNode htmlNode, []string classNames) HtmlNode
  • Description: Adiciona várias classes CSS a um elemento HTML.

Function: html.append

  • Signature: fn append(HtmlNode htmlNode, HtmlNode child) HtmlNode
  • Description: Anexa um elemento filho a um elemento HTML existente.

Function: html.appendText

  • Signature: fn appendText(HtmlNode htmlNode, string text) HtmlNode
  • Description: Anexa texto bruto a um elemento HTML.

Function: html.body

  • Signature: fn body() HtmlNode
  • Description: Cria um elemento <body>.

Function: html.button

  • Signature: fn button(string id, string title, string onClickFunction) HtmlNode
  • Description: Cria um elemento <button>.

Function: html.create

  • Signature: fn create(bool forceWhiteBackground) HtmlNode
  • Description: Cria um elemento HTML especializado com atributos e corpo opcionais.

Function: html.createElement

  • Signature: fn createElement(string tagName, bool isVoidTag) HtmlNode
  • Description: Cria um elemento HTML genérico pelo nome da tag.

Function: html.cssAttr

  • Signature: fn cssAttr(HtmlNode htmlNode, string name, string value) HtmlNode
  • Description: Aplica uma propriedade/estilo CSS a um elemento HTML.

Function: html.customElement

  • Signature: fn customElement(string tagName) HtmlNode
  • Description: Cria um elemento HTML personalizado (ex: <app></app>).

Function: html.div

  • Signature: fn div() HtmlNode
  • Description: Cria um elemento <div>.

Function: html.form

  • Signature: fn form() HtmlNode
  • Description: Cria um elemento <form>.

Function: html.h1

  • Signature: fn h1(string text) HtmlNode
  • Description: Cria um elemento <h1>.

Function: html.h2

  • Signature: fn h2(string text) HtmlNode
  • Description: Cria um elemento <h2>.

Function: html.h3

  • Signature: fn h3(string text) HtmlNode
  • Description: Cria um elemento <h3>.

Function: html.head

  • Signature: fn head() HtmlNode
  • Description: Cria um elemento <head>.

Function: html.img

  • Signature: fn img(string src, string alt) HtmlNode
  • Description: Cria um elemento <img>.

Function: html.input

  • Signature: fn input(string type, string name, string value) HtmlNode
  • Description: Cria um elemento <input>.

Function: html.label

  • Signature: fn label(string text) HtmlNode
  • Description: Cria um elemento <label>.

Function: html.li

  • Signature: fn li(string text) HtmlNode
  • Description: Cria um elemento <li> (item de lista).

  • Signature: fn link(string href) HtmlNode
  • Description: Cria um elemento <link>.

Function: html.meta

  • Signature: fn meta(string charset) HtmlNode
  • Description: Cria um elemento <meta>.

Function: html.p

  • Signature: fn p(string text) HtmlNode
  • Description: Cria um elemento <p> (parágrafo).

Function: html.script

  • Signature: fn script(string src, string content) HtmlNode
  • Description: Cria um elemento <script>.

Function: html.setAttr

  • Signature: fn setAttr(HtmlNode htmlNode, string name, string value) HtmlNode
  • Description: Define um atributo (ex: id, classe, src) em um elemento HTML.

Function: html.span

  • Signature: fn span() HtmlNode
  • Description: Cria um elemento <span>.

Function: html.style

  • Signature: fn style() HtmlNode
  • Description: Cria um elemento <style>.

Function: html.title

  • Signature: fn title(string text) HtmlNode
  • Description: Cria um elemento <title>.

Function: html.ul

  • Signature: fn ul() HtmlNode
  • Description: Cria um elemento <ul> (lista não ordenada).

Module: int

Function: int.parse

  • Signature: fn parse(any value) any?
  • Description: Analisa uma string ou número para um número inteiro.

Example:

nyl
i = int.parse("123")

Module: json

Function: json.atomicParse

  • Signature: fn atomicParse(string json) any
  • Description: Análise rápida e atômica de uma string JSON.

Function: json.isValid

  • Signature: fn isValid(string strInput) bool
  • Description: Verifica se uma string é um documento JSON válido.

Function: json.parse

  • Signature: fn parse(string json, any? targetType) any
  • Description: Analisa uma string JSON em um objeto Nyl (mapa ou array).

Example:

nyl
obj = json.parse('{"a": 1}')

Function: json.stringify

  • Signature: fn stringify(any obj) string
  • Description: Serializa um valor Nyl em uma string JSON.

Example:

nyl
json = json.stringify([1, 2, "três"])

Module: kv

Function: kv.clear

  • Signature: fn clear(KeyValueDB keyValueDB) void
  • Description: Remove todas as entradas do banco de dados.

Function: kv.create

  • Signature: fn create(string filePath, string? password) KeyValueDB
  • Description: Abre ou cria um banco de dados Chave-Valor persistente.

Function: kv.createDrop

  • Signature: fn createDrop(string filePath, string? password) KeyValueDB
  • Description: Cria um novo banco de dados Chave-Valor, sobrescrevendo qualquer um existente.

Function: kv.get

  • Signature: fn get(KeyValueDB keyValueDB, string key) any?
  • Description: Recupera um valor por sua chave do banco de dados.

Function: kv.remove

  • Signature: fn remove(KeyValueDB keyValueDB, string key) void
  • Description: Remove uma chave e seu valor do banco de dados.

Function: kv.set

  • Signature: fn set(KeyValueDB keyValueDB, string key, any value) void
  • Description: Armazena um valor associado a uma chave no banco de dados.

Function: kv.show

  • Signature: fn show(KeyValueDB keyValueDB, string? filterByKey) void
  • Description: Exibe o conteúdo do banco de dados em uma tabela formatada.

Function: kv.showInExplorer

  • Signature: fn showInExplorer(KeyValueDB keyValueDB) void
  • Description: Abre o local do arquivo do banco de dados no explorador de arquivos.

Module: long

Function: long.parse

  • Signature: fn parse(any value) any?
  • Description: Analisa uma string ou número para um número inteiro longo.

Example:

nyl
l = long.parse("1234567890")

Module: math

Function: math.abs

  • Signature: fn abs(number value) number
  • Description: Retorna o valor absoluto de um número.

Example:

nyl
v = math.abs(-5) // 5

Function: math.acos

  • Signature: fn acos(number value) number
  • Description: Retorna o ângulo cujo cosseno é o número especificado.

Example:

nyl
v = math.acos(1) // 0

Function: math.asin

  • Signature: fn asin(number value) number
  • Description: Retorna o ângulo cujo seno é o número especificado.

Example:

nyl
v = math.asin(0) // 0

Function: math.atan

  • Signature: fn atan(number value) number
  • Description: Retorna o ângulo cujo tangente é o número especificado.

Example:

nyl
v = math.atan(0) // 0

Function: math.ceil

  • Signature: fn ceil(number value) number
  • Description: Retorna o menor valor integral que é maior ou igual ao número especificado.

Example:

nyl
v = math.ceil(1.2) // 2

Function: math.cos

  • Signature: fn cos(number value) number
  • Description: Retorna o cosseno do ângulo especificado.

Example:

nyl
v = math.cos(0) // 1

Function: math.cosh

  • Signature: fn cosh(number value) number
  • Description: Retorna o cosseno hiperbólico do ângulo especificado.

Example:

nyl
v = math.cosh(0) // 1

Function: math.exp

  • Signature: fn exp(number value) number
  • Description: Retorna e elevado à potência especificada.

Example:

nyl
v = math.exp(1) // 2.718...

Function: math.floor

  • Signature: fn floor(number value) number
  • Description: Retorna o maior valor integral que é menor ou igual ao número especificado.

Example:

nyl
v = math.floor(1.8) // 1

Function: math.log

  • Signature: fn log(number value) number
  • Description: Retorna o logaritmo natural (base e) de um número especificado.

Example:

nyl
v = math.log(2.718) // ~1

Function: math.log10

  • Signature: fn log10(number value) number
  • Description: Retorna o logaritmo de base 10 de um número especificado.

Example:

nyl
v = math.log10(100) // 2

Function: math.round

  • Signature: fn round(number value) number
  • Description: Arredonda um valor para o inteiro mais próximo.

Example:

nyl
v = math.round(1.5) // 2

Function: math.sin

  • Signature: fn sin(number value) number
  • Description: Retorna o seno do ângulo especificado.

Example:

nyl
v = math.sin(0) // 0

Function: math.sinh

  • Signature: fn sinh(number value) number
  • Description: Retorna o seno hiperbólico do ângulo especificado.

Example:

nyl
v = math.sinh(0) // 0

Function: math.sqrt

  • Signature: fn sqrt(number value) number
  • Description: Calcula a raiz quadrada binária.

Example:

nyl
v = math.sqrt(16) // 4

Function: math.tan

  • Signature: fn tan(number value) number
  • Description: Retorna a tangente do ângulo especificado.

Example:

nyl
v = math.tan(0) // 0

Function: math.tanh

  • Signature: fn tanh(number value) number
  • Description: Retorna a tangente hiperbólica do ângulo especificado.

Example:

nyl
v = math.tanh(0) // 0

Module: net

Function: net.downloadFile

  • Signature: fn downloadFile(string url, bool silentlyFail, bool printErrOnConsole) []byte
  • Description: Baixa um arquivo de uma URL para um destino local.

Example:

nyl
net.downloadFile("https://example.com/imagem.png", "download.png")

Function: net.downloadFileAsync

  • Signature: fn downloadFileAsync(string url, bool silentlyFail, bool printErrOnConsole) NylTask
  • Description: Baixa um arquivo de uma URL de forma assíncrona.

Function: net.downloadFileInChunks

  • Signature: fn downloadFileInChunks(string url, string destPath, number chunkSize, bool silentlyFail) bool
  • Description: Baixa um arquivo em pedaços para um melhor gerenciamento de memória.

Function: net.downloadString

  • Signature: fn downloadString(string url, bool silentlyFail, bool printErrOnConsole) string?
  • Description: Baixa o conteúdo de uma URL como uma string.

Function: net.downloadStringAsync

  • Signature: fn downloadStringAsync(string url, bool silentlyFail, bool printErrOnConsole) NylTask
  • Description: Baixa o conteúdo de uma URL como uma string de forma assíncrona.

Function: net.getExternalIP

  • Signature: fn getExternalIP() string
  • Description: Recupera o endereço IP público da máquina atual.

Example:

nyl
ip = net.getExternalIP()

Function: net.getExternalIPAsync

  • Signature: fn getExternalIPAsync() NylTask
  • Description: Recupera o endereço IP público de forma assíncrona.

Function: net.getHostInfoJson

  • Signature: fn getHostInfoJson() string
  • Description: Recupera informações geográficas e técnicas sobre o IP atual no formato JSON.

Example:

nyl
info = net.getHostInfoJson()

Function: net.getHostInfoJsonAsync

  • Signature: fn getHostInfoJsonAsync() NylTask
  • Description: Recupera o JSON de informações do host de forma assíncrona.

Function: net.getLocalDns

  • Signature: fn getLocalDns() string?
  • Description: Retorna o endereço do servidor DNS primário da máquina.

Function: net.getLocalIP

  • Signature: fn getLocalIP(bool returnDns) string
  • Description: Retorna o endereço IP local (IPv4) da máquina.

Example:

nyl
ip = net.getLocalIP()

Function: net.getRealMacAddress

  • Signature: fn getRealMacAddress() string
  • Description: Retorna o endereço físico (MAC) da interface de rede ativa primária.

Function: net.httpDelete

  • Signature: fn httpDelete(string url, any? headers) HttpResult?
  • Description: Envia uma solicitação HTTP DELETE.

Function: net.httpDeleteAsync

  • Signature: fn httpDeleteAsync(string url, any? headers) NylTask
  • Description: Envia uma solicitação HTTP DELETE de forma assíncrona.

Function: net.httpGet

  • Signature: fn httpGet(string url, any? headers) HttpResult?
  • Description: Envia uma solicitação HTTP GET e retorna a resposta como uma string.

Example:

nyl
conteudo = net.httpGet("https://api.example.com/data")

Function: net.httpGetAsync

  • Signature: fn httpGetAsync(string url, any? headers) NylTask
  • Description: Envia uma solicitação HTTP GET de forma assíncrona.

Function: net.httpPatchJson

  • Signature: fn httpPatchJson(string url, any data, any? headers) HttpResult?
  • Description: Envia uma solicitação HTTP PATCH com um payload JSON.

Function: net.httpPatchJsonAsync

  • Signature: fn httpPatchJsonAsync(string url, any data, any? headers) NylTask
  • Description: Envia uma solicitação HTTP PATCH com JSON de forma assíncrona.

Function: net.httpPostForm

  • Signature: fn httpPostForm(string url, any data, any? headers) HttpResult?
  • Description: Envia uma solicitação HTTP POST com dados codificados em formulário.

Function: net.httpPostFormAsync

  • Signature: fn httpPostFormAsync(string url, any data, any? headers) NylTask
  • Description: Envia uma solicitação HTTP POST com formulário de forma assíncrona.

Function: net.httpPostJson

  • Signature: fn httpPostJson(string url, any data, any? headers) HttpResult?
  • Description: Envia uma solicitação HTTP POST com um payload JSON.

Example:

nyl
resp = net.httpPostJson("https://api.example.com", '{"id": 123}')

Function: net.httpPostJsonAsync

  • Signature: fn httpPostJsonAsync(string url, any data, any? headers) NylTask
  • Description: Envia uma solicitação HTTP POST com JSON de forma assíncrona.

Function: net.httpPutJson

  • Signature: fn httpPutJson(string url, any data, any? headers) HttpResult?
  • Description: Envia uma solicitação HTTP PUT com um payload JSON.

Function: net.httpPutJsonAsync

  • Signature: fn httpPutJsonAsync(string url, any data, any? headers) NylTask
  • Description: Envia uma solicitação HTTP PUT com JSON de forma assíncrona.

Function: net.isFileDownloadable

  • Signature: fn isFileDownloadable(string url) bool
  • Description: Verifica se uma URL aponta para um recurso para download verificando os cabeçalhos.

Function: net.isWebSocketActive

  • Signature: fn isWebSocketActive(string serverUrl) bool

Function: net.portInUse

  • Signature: fn portInUse(number port, bool silentlyFail) bool
  • Description: Verifica se uma porta TCP específica está em uso no momento.

Function: net.uploadFile

  • Signature: fn uploadFile(string url, []byte fileData, bool silentlyFail) bool

Function: net.validUrl

  • Signature: fn validUrl(string url) bool
  • Description: Verifica se uma string é uma URL válida e bem formada.

Module: number

Function: number.parse

  • Signature: fn parse(any value) any?
  • Description: Analisa uma string para um número de ponto flutuante.

Example:

nyl
n = number.parse("123.45")

Module: nylweb

Function: nylweb.createClient

  • Signature: fn createClient(string uri, bool reconnect) NylClient
  • Description: Criar Instância de NylClient

Function: nylweb.createServer

  • Signature: fn createServer(number port, bool useStaticFile, string basePath, string uri) NylServer
  • Description: Criar Instância de NylServer
  • Signature: fn createServer(number port, string uri) NylServer
  • Description: Criar NylServer com serviço de arquivos estáticos

Module: os

Module: os.windows

Function: os.windows.createTaskScheduler
  • Signature: fn createTaskScheduler(string actionPath, string? actionArguments, string appDirectory, string taskDescription, number delaySec, number intervalSec, bool onlyCreateIfNotExists, string? Author) datetime?
  • Description: Cria uma tarefa agendada no Windows para executar uma ação específica.

Example:

nyl
os.windows.createTaskScheduler("C:/App/run.exe", "--start", "C:/App", "Minha Tarefa Diaria", 0, 1440)

Function: os.windows.elevatePrivilege
  • Signature: fn elevatePrivilege(string? processName, string? args) bool
  • Description: Tenta elevar os privilégios do processo para Administrador. Reinicia o aplicativo se necessário.

Example:

nyl
os.windows.elevatePrivilege()

Function: os.windows.getBiosInfo
  • Signature: fn getBiosInfo() string
  • Description: Retorna informações combinadas sobre o BIOS do sistema.

Example:

nyl
bios = os.windows.getBiosInfo()

Function: os.windows.getClipboardText
  • Signature: fn getClipboardText() string?
  • Description: Recupera texto da área de transferência do Windows.

Example:

nyl
texto = os.windows.getClipboardText()

Function: os.windows.getGpuName
  • Signature: fn getGpuName() string
  • Description: Recupera o nome e a versão do driver da GPU/Controlador de Vídeo principal.

Example:

nyl
gpu = os.windows.getGpuName()

Function: os.windows.getGpuNameByRegistry
  • Signature: fn getGpuNameByRegistry() string
  • Description: Recupera o nome da GPU diretamente do Registro do Windows.

Example:

nyl
gpu_reg = os.windows.getGpuNameByRegistry()

Function: os.windows.getManufacturer
  • Signature: fn getManufacturer() []string
  • Description: Retorna o fabricante e o modelo do sistema.

Example:

nyl
info = os.windows.getManufacturer() // [Fabricante, Modelo]

Function: os.windows.getMotherboardFromRegistry
  • Signature: fn getMotherboardFromRegistry() string
  • Description: Recupera informações da placa-mãe do registro do Windows.

Example:

nyl
placa_reg = os.windows.getMotherboardFromRegistry()

Function: os.windows.getMotherboardInfo
  • Signature: fn getMotherboardInfo() string
  • Description: Retorna informações combinadas sobre a placa-mãe (BaseBoard).

Example:

nyl
placa = os.windows.getMotherboardInfo()

Function: os.windows.getProcessorFromRegistry
  • Signature: fn getProcessorFromRegistry() string
  • Description: Recupera o nome da CPU diretamente do registro do Windows.

Example:

nyl
cpu_reg = os.windows.getProcessorFromRegistry()

Function: os.windows.getProcessorName
  • Signature: fn getProcessorName() string
  • Description: Retorna o nome oficial de marketing da CPU.

Example:

nyl
cpu = os.windows.getProcessorName()

Function: os.windows.getRegistryValue
  • Signature: fn getRegistryValue(string hive, string subKey, string valueName) any?
  • Description: Obtém um valor do Registro do Windows.

Example:

nyl
val = os.windows.getRegistryValue("HKEY_LOCAL_MACHINE", "SOFTWARE/...", "Valor")

Function: os.windows.getScreenshotsBase64
  • Signature: fn getScreenshotsBase64() []string
  • Description: Captura capturas de tela de todos os monitores conectados como strings PNG codificadas em Base64.

Example:

nyl
imagens = os.windows.getScreenshotsBase64()

Function: os.windows.getScreenshotsBytes
  • Signature: fn getScreenshotsBytes() [][]byte
  • Description: Captura capturas de tela de todos os monitores conectados como arrays de bytes brutos (PNG).

Example:

nyl
imagens_brutas = os.windows.getScreenshotsBytes()

Function: os.windows.getSystemErrorStr
  • Signature: fn getSystemErrorStr(number codeError) string
  • Description: Converte um código de erro do sistema Windows em uma mensagem legível por humanos.

Example:

nyl
msg = os.windows.getSystemErrorStr(5) // "Acesso negado"

Function: os.windows.getWindowsFromRegistry
  • Signature: fn getWindowsFromRegistry() string
  • Description: Recupera a marca da versão do Windows diretamente do registro.

Example:

nyl
win_reg = os.windows.getWindowsFromRegistry()

Function: os.windows.getWindowsName
  • Signature: fn getWindowsName() string
  • Description: Retorna um nome descritivo da versão do Windows (ex: Windows 11 Enterprise).

Example:

nyl
nome_win = os.windows.getWindowsName()

Function: os.windows.isAdmin
  • Signature: fn isAdmin() bool
  • Description: Verifica se o processo atual está sendo executado com privilégios de Administrador.

Example:

nyl
if os.windows.isAdmin() { ... }

Function: os.windows.isProcessDPIAware
  • Signature: fn isProcessDPIAware() bool
  • Description: Verifica se o processo atual reconhece DPI (DPI-aware) no Windows.

Example:

nyl
reconhece_dpi = os.windows.isProcessDPIAware()

Function: os.windows.isSystemLocked
  • Signature: fn isSystemLocked() bool
  • Description: Verifica se a área de trabalho do Windows está bloqueada.

Example:

nyl
bloqueado = os.windows.isSystemLocked()

Function: os.windows.isVirtualGPU
  • Signature: fn isVirtualGPU() bool
  • Description: Verifica se o controlador de vídeo principal indica uma GPU virtualizada (ex: Hyper-V, Área de Trabalho Remota).

Example:

nyl
if os.windows.isVirtualGPU() { println("Usando GPU Virtual") }

Function: os.windows.isVirtualMachine
  • Signature: fn isVirtualMachine() bool
  • Description: Verifica se o sistema operacional está sendo executado dentro de uma Máquina Virtual.

Example:

nyl
if os.windows.isVirtualMachine() { println("Executando em VM") }

Function: os.windows.isVirtualManufacturer
  • Signature: fn isVirtualManufacturer() bool
  • Description: Verifica se o fabricante do hardware indica um ambiente virtual.

Example:

nyl
eh_virt = os.windows.isVirtualManufacturer()

Function: os.windows.msgBox
  • Signature: fn msgBox(string text, string caption) void
  • Description: Exibe uma caixa de mensagem padrão do Windows com um botão OK.

Example:

nyl
os.windows.msgBox("Operação bem-sucedida", "Info")

Function: os.windows.msgBoxErr
  • Signature: fn msgBoxErr(string text, string caption) void
  • Description: Exibe uma caixa de mensagem de erro padrão do Windows com um ícone.

Example:

nyl
os.windows.msgBoxErr("Algo deu errado!", "Erro Crítico")

Function: os.windows.programFilesPath
  • Signature: fn programFilesPath() string
  • Description: Retorna o caminho do Program Files.

Function: os.windows.programFilesX86Path
  • Signature: fn programFilesX86Path() string
  • Description: Retorna o caminho do Program Files (x86).

Function: os.windows.resourceInfo
  • Signature: fn resourceInfo(string filename) void
  • Description: Imprime metadados e informações de manifesto de um arquivo PE do Windows (exe/dll).

Example:

nyl
os.windows.resourceInfo("target.exe")

Function: os.windows.setClipboardText
  • Signature: fn setClipboardText(string text) bool
  • Description: Copia texto para a área de transferência do Windows.

Example:

nyl
os.windows.setClipboardText("Olá de Nyl!")

Function: os.windows.setRegistryValue
  • Signature: fn setRegistryValue(string hive, string subKey, string valueName, any value) any?
  • Description: Define um valor no Registro do Windows.

Example:

nyl
os.windows.setRegistryValue("HKEY_CURRENT_USER", "SOFTWARE/MinhaAppNyl", "Config", 1)

Function: os.appDataPath

  • Signature: fn appDataPath() string
  • Description: Retorna o caminho do Application Data (Roaming).

Example:

nyl
caminho = os.appDataPath()

Function: os.arch

  • Signature: fn arch() string
  • Description: Obtém a string de arquitetura do SO

Example:

nyl
arquitetura = os.arch() // "X64"

Function: os.convertImageToPngBase64

  • Signature: fn convertImageToPngBase64(string path) string?
  • Description: Converte um arquivo de imagem em uma string PNG codificada em Base64.

Example:

nyl
base64 = os.convertImageToPngBase64("caminho/para/imagem.jpg")

Function: os.copyFile

  • Signature: fn copyFile(string source, string dest, bool overwrite) void
  • Description: Copia um arquivo existente para um novo arquivo.

Example:

nyl
os.copyFile("origem.txt", "destino.txt", true)

Function: os.createDir

  • Signature: fn createDir(string path, string? atrib) bool
  • Description: Cria todos os diretórios e subdiretórios no caminho especificado, a menos que já existam.

Example:

nyl
os.createDir("C:/NovaPasta")

Function: os.createMutex

  • Signature: fn createMutex(string mutexName) bool
  • Description: Cria um Mutex de sistema

Example:

nyl
novo = os.createMutex("MinhaAppUnica")

Function: os.currentDir

  • Signature: fn currentDir() string
  • Description: Obtém o diretório funcional atual da aplicação.

Example:

nyl
dir = os.currentDir()

Function: os.deleteAllFilesOfPath

  • Signature: fn deleteAllFilesOfPath(string folderPath, bool allDirectories) bool
  • Description: Exclui todos os arquivos no caminho especificado.

Example:

nyl
os.deleteAllFilesOfPath("C:/Temp/Cache", true)

Function: os.dirExists

  • Signature: fn dirExists(string path) bool
  • Description: Determina se o caminho fornecido refere-se a um diretório existente no disco.

Example:

nyl
if os.dirExists("C:/Windows") { ... }

Function: os.exec

  • Signature: fn exec(string name, string? args, string? verb, string? workingDirectory) string
  • Description: Executa um processo e retorna sua saída padrão como uma string.

Example:

nyl
saida = os.exec("git", "--version")

Function: os.exitCode

  • Signature: fn exitCode(Process process) number

Function: os.fileDelete

  • Signature: fn fileDelete(string path) bool
  • Description: Exclui o arquivo especificado.

Example:

nyl
os.fileDelete("arquivo_antigo.txt")

Function: os.fileExists

  • Signature: fn fileExists(string path) bool
  • Description: Verifica se um arquivo existe.

Example:

nyl
if os.fileExists("config.json") { ... }

Function: os.fileReadBytes

  • Signature: fn fileReadBytes(string path, number bufferSize) []byte
  • Description: Lê todo o conteúdo de um arquivo em um array de bytes.

Example:

nyl
dados = os.fileReadBytes("imagem.png")

Function: os.fileReadText

  • Signature: fn fileReadText(string path, number bufferSize) string
  • Description: Lê todo o conteúdo de um arquivo em uma string.

Example:

nyl
texto = os.fileReadText("notas.txt")

Function: os.fileWriteBytes

  • Signature: fn fileWriteBytes(string path, []byte data, number bufferSize) bool
  • Description: Grava um array de bytes em um arquivo, criando-o ou substituindo-o.

Example:

nyl
os.fileWriteBytes("saida.bin", dados)

Function: os.fileWriteText

  • Signature: fn fileWriteText(string path, string contents, bool append, number bufferSize) bool
  • Description: Grava uma string em um arquivo. Suporta anexação.

Example:

nyl
os.fileWriteText("log.txt", "nova entrada de log\n", true)

Function: os.findFilesInFolder

  • Signature: fn findFilesInFolder(string folderPath, string searchPattern, bool allDirectories, []string subFilter) []string
  • Description: Localiza todos os arquivos em uma pasta que correspondem a um padrão de pesquisa.

Example:

nyl
arquivos = os.findFilesInFolder("C:/Docs", "*.txt", true)

Function: os.findFilesInFolderWithFilter

  • Signature: fn findFilesInFolderWithFilter(string folderPath, list? subFilter) []string
  • Description: Localiza todos os arquivos em uma pasta aplicando um filtro de substring ao caminho completo.

Example:

nyl
arquivos = os.findFilesInFolderWithFilter("C:/Docs", [".txt", ".pdf"])

Function: os.getAvailableDiskFreeSpace

  • Signature: fn getAvailableDiskFreeSpace() string
  • Description: Retorna o espaço livre em disco disponível na unidade principal do sistema como uma string formatada.

Example:

nyl
livre = os.getAvailableDiskFreeSpace()

Function: os.getAvailableMemory

  • Signature: fn getAvailableMemory(bool format) ulong | string
  • Description: Obtém a memória física disponível

Example:

nyl
disponivel = os.getAvailableMemory()

Function: os.getCompiledDotnetVersion

  • Signature: fn getCompiledDotnetVersion() string
  • Description: Obtém a descrição do .NET Framework

Example:

nyl
ver = os.getCompiledDotnetVersion()

Function: os.getCurrentProcessName

  • Signature: fn getCurrentProcessName() string
  • Description: Retorna o nome do processo em execução no momento.

Example:

nyl
nome = os.getCurrentProcessName()

Function: os.getDir

  • Signature: fn getDir(string file) string?
  • Description: Retorna as informações do diretório para a string de caminho especificada.

Example:

nyl
dir = os.getDir("C:/Docs/arquivo.txt") // "C:/Docs"

Function: os.getDisksInfoAsJson

  • Signature: fn getDisksInfoAsJson() string
  • Description: Retorna informações sobre todas as unidades prontas no sistema como uma string JSON.

Example:

nyl
json = os.getDisksInfoAsJson()

Function: os.getDiskTotalSize

  • Signature: fn getDiskTotalSize() string
  • Description: Retorna o tamanho total da unidade de disco principal do sistema como uma string formatada.

Example:

nyl
total = os.getDiskTotalSize()

Function: os.getEnvVar

  • Signature: fn getEnvVar(string varName, string variableTarget) string
  • Description: Obtém o valor de uma variável de ambiente.

Example:

nyl
caminho = os.getEnvVar("PATH")

Function: os.getFileName

  • Signature: fn getFileName(string pathfile) string
  • Description: Retorna o nome do arquivo e a extensão de uma string de caminho.

Example:

nyl
nome = os.getFileName("C:/Docs/arquivo.txt") // "arquivo.txt"

Function: os.getMachineName

  • Signature: fn getMachineName() string
  • Description: Obtém o nome da máquina

Example:

nyl
host = os.getMachineName()

Function: os.getProcessArch

  • Signature: fn getProcessArch() string
  • Description: Obtém a string da arquitetura do processo (x64 ou x86)

Example:

nyl
arquitetura = os.getProcessArch()

Function: os.getProcessByName

  • Signature: fn getProcessByName(string processName) Process?
  • Description: Recupera um objeto Process pelo seu nome.

Example:

nyl
proc = os.getProcessByName("nyl")

Function: os.getProcessByPid

  • Signature: fn getProcessByPid(number pid) ProcessInfo?
  • Description: Recupera informações sobre um processo usando seu ID de Processo (PID).

Example:

nyl
pinfo = os.getProcessByPid(1234)

Function: os.getProcessDir

  • Signature: fn getProcessDir() string
  • Description: Retorna o caminho do diretório do executável do processo atual.

Example:

nyl
dir = os.getProcessDir()

Function: os.getProcesses

  • Signature: fn getProcesses() list
  • Description: Retorna uma lista de todos os processos em execução no momento com informações básicas.

Example:

nyl
procs = os.getProcesses()

Function: os.getProcessorCount

  • Signature: fn getProcessorCount() number
  • Description: Obtém o número de processadores/núcleos

Example:

nyl
nucleos = os.getProcessorCount()

Function: os.getProcessProductName

  • Signature: fn getProcessProductName(string filterByProcNameModule, string? processName) string
  • Description: Recupera os metadados ProductName de um processo em execução ou de seus módulos.

Example:

nyl
nome = os.getProcessProductName("nyl")

Function: os.getProcessProductVersion

  • Signature: fn getProcessProductVersion(string filterByProcNameModule, string? processName) string
  • Description: Recupera os metadados ProductVersion de um processo em execução ou de seus módulos.

Example:

nyl
ver = os.getProcessProductVersion("nyl")

Function: os.getTotalMemory

  • Signature: fn getTotalMemory(bool format) ulong | string
  • Description: Obtém a memória física total

Example:

nyl
total = os.getTotalMemory()

Function: os.getUptime

  • Signature: fn getUptime(bool isFormatted) any
  • Description: Obtém o tempo de atividade do sistema

Example:

nyl
tempo = os.getUptime() // ex: "05:30:15"

Function: os.hasFileWritePermission

  • Signature: fn hasFileWritePermission(string filePath) bool
  • Description: Verifica se o processo atual tem permissão de gravação para o arquivo.

Example:

nyl
podeGravar = os.hasFileWritePermission("dados.db")

Function: os.is64bitOS

  • Signature: fn is64bitOS() bool
  • Description: Verifica se o SO é de 64 bits

Example:

nyl
if os.is64bitOS() { println("SO de 64 bits") }

Function: os.is64bitProcess

  • Signature: fn is64bitProcess() bool
  • Description: Verifica se o processo atual é de 64 bits

Example:

nyl
if os.is64bitProcess() { println("Processo de 64 bits") }

Function: os.isAndroid

  • Signature: fn isAndroid() bool
  • Description: Verifica se o SO é Android

Example:

nyl
if os.isAndroid() { println("Executando no Android") }

Function: os.isBrowser

  • Signature: fn isBrowser() bool
  • Description: Verifica se o SO é o Navegador (WASM)

Example:

nyl
if os.isBrowser() { println("Executando no Navegador") }

Function: os.isLinux

  • Signature: fn isLinux() bool
  • Description: Verifica se o SO é Linux

Example:

nyl
if os.isLinux() { println("Executando no Linux") }

Function: os.isMacos

  • Signature: fn isMacos() bool
  • Description: Verifica se o SO é MacOS

Example:

nyl
if os.isMacos() { println("Executando no MacOS") }

Function: os.isSmallDisk

  • Signature: fn isSmallDisk() bool
  • Description: Verifica se o tamanho total do disco principal é menor ou igual a 70GB.

Example:

nyl
if os.isSmallDisk() { println("Disco pequeno detectado") }

Function: os.isWindows

  • Signature: fn isWindows() bool
  • Description: Verifica se o SO é Windows

Example:

nyl
if os.isWindows() { println("Executando no Windows") }

Function: os.killProcessByName

  • Signature: fn killProcessByName(string processName, bool killChilds) void
  • Description: Localiza e encerra todos os processos com o nome fornecido.

Example:

nyl
os.killProcessByName("calc")

Function: os.killProcessByPid

  • Signature: fn killProcessByPid(number pid, bool killChilds) void
  • Description: Encerra um processo específico pelo seu PID.

Example:

nyl
os.killProcessByPid(1234)

Function: os.localAppDataPath

  • Signature: fn localAppDataPath() string
  • Description: Retorna o caminho do Local Application Data.

Example:

nyl
caminho = os.localAppDataPath()

Function: os.moveFile

  • Signature: fn moveFile(string source, string dest, bool overwrite) void
  • Description: Move um arquivo existente para um novo local.

Example:

nyl
os.moveFile("antigo.txt", "novo_local.txt", true)

Function: os.name

  • Signature: fn name() string
  • Description: Obtém a string de descrição do SO

Example:

nyl
nome = os.name() // "Windows 11 ..."

Function: os.newProcess

  • Signature: fn newProcess(string processExec, string? args, Value? outputReceived, Value? errorReceived, Value? onExit) Process?
  • Description: Inicia um novo processo genérico com redirecionamento assíncrono de saída/erro e retorno de chamada na saída.

Example:

nyl
os.newProcess("git", "status", fn(out) => println(out), nil, fn(code) => println("Encerrado: {code}"))

Function: os.newTerminal

  • Signature: fn newTerminal(string? args, Value? outputReceived, Value? errorReceived) Process?
  • Description: Inicia um novo processo de terminal interativo (cmd.exe ou bash) com redirecionamento de saída assíncrono.

Example:

nyl
sh = os.newTerminal(nil, fn(out) => println(out))

Function: os.newTerminalPS

  • Signature: fn newTerminalPS(string? args, Value? outputReceived, Value? errorReceived) Process?
  • Description: Inicia um novo processo de terminal PowerShell interativo com redirecionamento de saída assíncrono.

Example:

nyl
ps = os.newTerminalPS(nil, fn(out) => println(out))

Function: os.pathCombine

  • Signature: fn pathCombine([]string paths) string
  • Description: Combina várias strings em um caminho.

Example:

nyl
caminho = os.pathCombine("C:", "Usuarios", "Docs")

Function: os.processExists

  • Signature: fn processExists(string processName) bool
  • Description: Verifica se um processo com o nome fornecido está em execução.

Example:

nyl
if os.processExists("chrome") { ... }

Function: os.run

  • Signature: fn run(string name, string? args, bool createNoWindow, string? workingDirectory, string? verb) Process?
  • Description: Executa um processo e retorna o objeto Process. Pode ser configurado para rodar em segundo plano.

Example:

nyl
proc = os.run("notepad.exe", "arquivo.txt")

Function: os.searchTermOurFilesInFolder

  • Signature: fn searchTermOurFilesInFolder(string searchTermInFile, string folderPath, string searchPattern, bool firstOccurrence, bool allDirectories, []string subFilter) []string
  • Description: Pesquisa por um termo dentro de arquivos em uma pasta.

Example:

nyl
correspondencias = os.searchTermOurFilesInFolder("todo", "C:/Projeto", "*.nyl")

Function: os.searchTermOurFilesInFolderWithFilter

  • Signature: fn searchTermOurFilesInFolderWithFilter(string searchTermInFile, string folderPath, list? subFilter) []string
  • Description: Pesquisa por um termo dentro de arquivos em uma pasta com subfiltro.

Example:

nyl
correspondencias = os.searchTermOurFilesInFolderWithFilter("todo", "C:/Projeto", [".nyl"])

Function: os.setEnvVar

  • Signature: fn setEnvVar(string varName, string value, string variableTarget) bool
  • Description: Define o valor de uma variável de ambiente.

Example:

nyl
os.setEnvVar("MINHA_VAR", "valor")

Function: os.SIMD

  • Signature: fn SIMD() bool
  • Description: Verifica suporte a SIMD

Example:

nyl
if os.SIMD() { println("SIMD habilitado") }

Function: os.sleep

  • Signature: fn sleep(number msTimeOut) void
  • Description: Para a execução da thread por milissegundos

Example:

nyl
os.sleep(1000) // Dorme por 1 segundo

Function: os.startProcess

  • Signature: fn startProcess(string fileName, string verb) bool
  • Description: Inicia um arquivo usando ShellExecute (ex: abre um documento em seu aplicativo padrão).

Example:

nyl
os.startProcess("leia-me.txt")

Function: os.stopWatchProcesses

  • Signature: fn stopWatchProcesses(ProcessMonitorHandle handle) void
  • Description: Para um monitor de processo

Function: os.tempFileExtStr

  • Signature: fn tempFileExtStr() string
  • Description: Cria um arquivo temporário vazio e com nome exclusivo no disco e retorna seu caminho (com extensão).

Example:

nyl
arquivo = os.tempFileExtStr()

Function: os.tempFileStr

  • Signature: fn tempFileStr() string
  • Description: Cria um arquivo temporário vazio e com nome exclusivo no disco e retorna seu caminho (sem extensão).

Example:

nyl
arquivo = os.tempFileStr()

Function: os.tempPath

  • Signature: fn tempPath() string
  • Description: Retorna o caminho da pasta temporária do usuário atual.

Example:

nyl
tmp = os.tempPath()

Function: os.wait

  • Signature: fn wait(Process process) void

Function: os.watchProcesses

  • Signature: fn watchProcesses(list names, any onStart, any onStop, number intervalMs) ProcessMonitorHandle
  • Description: Monitora eventos de início/parada de processos por nome

Module: ptr

Function: ptr.add

  • Signature: fn add(nint ptr, number offset) nint
  • Description: Adiciona um deslocamento (em bytes) a um ponteiro.

Function: ptr.fromInt

  • Signature: fn fromInt(number num) nint
  • Description: Cria um ponteiro a partir de um inteiro de 64 bits.

Function: ptr.isNil

  • Signature: fn isNil(nint ptr) bool
  • Description: Verifica se um ponteiro é nulo.

Function: ptr.nil

  • Signature: fn nil() nint
  • Description: Retorna um ponteiro nulo (IntPtr.Zero).

Function: ptr.sub

  • Signature: fn sub(nint ptr, number offset) nint
  • Description: Subtrai um deslocamento de um ponteiro.

Function: ptr.toInt

  • Signature: fn toInt(nint ptr) number
  • Description: Converte um ponteiro em sua representação inteira de 64 bits.

Module: socketClient

Function: socketClient.close

  • Signature: fn close(SocketClient socketClient) bool
  • Description: Fecha a conexão de socket atual.

Function: socketClient.connect

  • Signature: fn connect(SocketClient socketClient) bool
  • Description: Tenta se conectar a um Servidor de Socket no IP e porta especificados.

Function: socketClient.create

  • Signature: fn create(string ipAddress, number port, ProtocolType protocol, bool reconnect) SocketClient?
  • Description: Cria uma nova instância de Cliente de Socket.

Function: socketClient.isReconnExhausted

  • Signature: fn isReconnExhausted(SocketClient socketClient) bool
  • Description: Verifica se as tentativas de reconexão foram esgotadas.

Function: socketClient.onConnect

  • Signature: fn onConnect(SocketClient client, fn onConnect) bool
  • Description: Define um callback para quando o cliente se conecta a um servidor.

Function: socketClient.onDisconnect

  • Signature: fn onDisconnect(SocketClient socketClient, fn onDisconnect) bool
  • Description: Define um callback para quando o cliente é desconectado.

Function: socketClient.onMessage

  • Signature: fn onMessage(SocketClient socketClient, fn onMessage) bool
  • Description: Define um callback para quando o cliente recebe uma mensagem do servidor.

Function: socketClient.retryWithNewIpAddress

  • Signature: fn retryWithNewIpAddress(SocketClient socketClient, string ipAddress, number port) bool
  • Description: Tenta se reconectar ao servidor usando um endereço IP diferente.

Function: socketClient.sendMessage

  • Signature: fn sendMessage(SocketClient socketClient, string message) bool
  • Description: Envia uma mensagem para o servidor conectado.

Module: socketServer

Function: socketServer.clientExists

  • Signature: fn clientExists(SocketServer server, string clientId) bool
  • Description: Verifica se um ID de cliente específico está conectado no momento.

Function: socketServer.create

  • Signature: fn create(string ipAddress, number port, string protocol) SocketServer
  • Description: Cria uma nova instância de Servidor de Socket.

Function: socketServer.getClient

  • Signature: fn getClient(SocketServer server, string clientId) any?
  • Description: Recupera informações sobre um cliente conectado específico.

Function: socketServer.getClients

  • Signature: fn getClients(SocketServer server) list
  • Description: Retorna uma lista de IDs de todos os clientes conectados no momento.

Function: socketServer.listen

  • Signature: fn listen(SocketServer server) bool
  • Description: Começa a ouvir conexões de entrada em uma porta específica.

Function: socketServer.onConnectServer

  • Signature: fn onConnectServer(SocketServer server, fn onConnect) SocketServer
  • Description: Define um callback para quando um cliente se conecta ao servidor.

Function: socketServer.onDisconnectServer

  • Signature: fn onDisconnectServer(SocketServer server, fn onDisconnect) SocketServer
  • Description: Define um callback para quando um cliente se desconecta do servidor.

Function: socketServer.onMessageServer

  • Signature: fn onMessageServer(SocketServer server, fn onMessage) SocketServer
  • Description: Define um callback para quando o servidor recebe uma mensagem de um cliente.

Function: socketServer.sendMessageServer

  • Signature: fn sendMessageServer(SocketServer server, string clientId, string message) void
  • Description: Envia uma mensagem para um cliente conectado específico.

Function: socketServer.stopServer

  • Signature: fn stopServer(SocketServer server) bool
  • Description: Para o Servidor de Socket e fecha todas as conexões.

Module: string

Function: string.parse

  • Signature: fn parse(any value) any?
  • Description: Converte um valor em sua representação de string.

Example:

nyl
s = string.parse(123)

Module: telegram

Function: telegram.botInfo

  • Signature: fn botInfo(TgBotApi? tgBotApi) TgBotResponse?
  • Description: Recupera informações sobre o robô (getMe).

Function: telegram.botInit

  • Signature: fn botInit(string token, number chatId) TgBotApi?
  • Description: Inicializa uma instância do Robô do Telegram com token e ID de chat padrão.

Function: telegram.botNextUpdatesCallback

  • Signature: fn botNextUpdatesCallback(TgBotApi? tgBotApi, any functionCallback, number periodInSecs) void
  • Description: Inicia um loop assíncrono para processar mensagens recebidas do Telegram via callback.

Function: telegram.botNextUpdatesMessage

  • Signature: fn botNextUpdatesMessage(TgBotApi? tgBotApi) string?
  • Description: Recupera a próxima mensagem pendente da fila de atualizações do Telegram.

Function: telegram.botSendMessage

  • Signature: fn botSendMessage(TgBotApi? tgBotApi, string message) bool
  • Description: Envia uma mensagem de texto via robô do Telegram.

Function: telegram.botUploadFileFromMemory

  • Signature: fn botUploadFileFromMemory(TgBotApi? tgBotApi, []byte bytes, string caption) bool
  • Description: Envia um arquivo de um array de bytes para um chat do Telegram.

Function: telegram.botUploadFileFromPath

  • Signature: fn botUploadFileFromPath(TgBotApi? tgBotApi, string path, string caption) bool
  • Description: Envia um arquivo de um caminho local para um chat do Telegram.

Function: telegram.botUploadImageFromMemory

  • Signature: fn botUploadImageFromMemory(TgBotApi? tgBotApi, []byte bytes, string caption) bool
  • Description: Envia uma imagem de um array de bytes para um chat do Telegram.

Function: telegram.botUploadImageFromPath

  • Signature: fn botUploadImageFromPath(TgBotApi? tgBotApi, string path, string caption) bool
  • Description: Envia uma imagem de um caminho local para um chat do Telegram.

Module: template

Function: template.render

  • Signature: fn render(string html, any? data, bool indent) string?
  • Description: Renderiza uma string de template HTML substituindo marcadores pelos dados de um objeto Nyl (mapa, instância de type ou lista).

Example:

nyl
type User { string name, int age, bool active }
page = { "title": "Minha Página", "users": [User("Alice", 25, true), User("Bob", 30, false)] }
html = "<h1>{{title}}</h1><ul nyl-for="user in users"><li>{{user.name}} ({{user.age}})</li></ul>"
rendered = template.render(html, page)
  • Signature: fn render(string htmlPage, string htmlPart, any? data, bool indent) string?
  • Description: Renderiza uma página HTML com layout e um template parcial de corpo. O layout utiliza @body para marcar onde o conteúdo parcial será inserido.

Example:

nyl
layout = "<html><body>@body</body></html>"
parcial = "<h1>{{title}}</h1>"
dados = { "title": "Olá" }
rendered = template.renderLayout(layout, parcial, dados)

Module: web3

Function: web3.stopWatchContract

  • Signature: fn stopWatchContract(Web3MonitorHandle handle) void

Function: web3.watchContract

  • Signature: fn watchContract(string contractAddress, string keyTag, any onChange, any onIncompatible, string currentVersion, bool autoEval, number intervalSecs, string? realm, string? backupPath, []string networks) Web3MonitorHandle

Module: webview

Function: webview.create

  • Signature: fn create(string source, string title, number width, number height) NylWebViewWindow
  • Description: Cria uma instância de WebView de alto desempenho para exibir conteúdo HTML/web.

Module: zip

Function: zip.compressBytesWithPrefix

  • Signature: fn compressBytesWithPrefix([]byte input, string prefix) []byte
  • Description: Comprime um array de bytes usando GZip e adiciona um prefixo personalizado (padrão: $zc).

Example:

nyl
comp = zip.compressBytesWithPrefix("meusDados".toBytes())

Function: zip.createEntryFromBytes

  • Signature: fn createEntryFromBytes(string entryName, []byte contentBytes, string? password, string? comment) []byte
  • Description: Cria um arquivo ZIP de entrada única na memória a partir de um array de bytes.

Example:

nyl
dados_zip = zip.createEntryFromBytes("arquivo.txt", "conteudo".toBytes())

Function: zip.createEntryFromFolder

  • Signature: fn createEntryFromFolder(string folderPath, string? zipName, string? password, string? comment) []byte
  • Description: Cria um arquivo ZIP na memória (array de bytes) a partir do conteúdo de uma pasta.

Example:

nyl
dados = zip.createEntryFromFolder("C:/Configs")

Function: zip.createFromFolder

  • Signature: fn createFromFolder(string folderPath, string? zipNameOrLocation, string? password, string? comment) bool
  • Description: Cria um arquivo ZIP a partir do conteúdo de uma pasta.

Example:

nyl
zip.createFromFolder("C:/Projeto", "C:/Backups/Projeto.zip")

Function: zip.decompressBytesWithPrefix

  • Signature: fn decompressBytesWithPrefix([]byte input, string prefix) []byte
  • Description: Descompacta um array de bytes que foi compactado com um prefixo específico.

Example:

nyl
bruto = zip.decompressBytesWithPrefix(comp)

Function: zip.isCompressedBytesWithPrefix

  • Signature: fn isCompressedBytesWithPrefix([]byte input, string prefix) bool
  • Description: Verifica se um array de bytes começa com o prefixo de compactação especificado.

Example:

nyl
if zip.isCompressedBytesWithPrefix(dados) { ... }

Function: zip.isFileFromBytes

  • Signature: fn isFileFromBytes([]byte zipFileData) bool
  • Description: Verifica se o array de bytes fornecido representa um arquivo ZIP válido.

Example:

nyl
if zip.isFileFromBytes(dados) { ... }

Function: zip.unzipBytesToFolder

  • Signature: fn unzipBytesToFolder([]byte zipFileData, string destinationPath, string? password) bool
  • Description: Extrai um arquivo ZIP da memória (array de bytes) para uma pasta de destino.

Example:

nyl
zip.unzipBytesToFolder(dados_zip, "saida/")

Function: zip.unzipEntryToBytes

  • Signature: fn unzipEntryToBytes([]byte zipFileData, string? password) []byte
  • Description: Extrai a primeira entrada de um arquivo ZIP na memória diretamente para um array de bytes.

Example:

nyl
dados_brutos = zip.unzipEntryToBytes(dados_zip)

Function: zip.unzipFileToFolder

  • Signature: fn unzipFileToFolder(string zipFilePath, string destinationPath, string? password) bool
  • Description: Extrai todo o conteúdo de um arquivo ZIP para uma pasta de destino.

Example:

nyl
zip.unzipFileToFolder("dados.zip", "extraido/")