@lizard-build/cli 4.0.96 → 4.0.98
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/commands/fn.d.ts +33 -0
- package/dist/commands/fn.js +596 -0
- package/dist/commands/fn.js.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/lib/skills-data.generated.js +2 -1
- package/dist/lib/skills-data.generated.js.map +1 -1
- package/dist/lib/updater.d.ts +1 -1
- package/dist/lib/updater.js +1 -1
- package/package.json +1 -1
- package/skill-data/core/SKILL.md +8 -2
- package/skill-data/core/references/functions.md +112 -0
- package/src/commands/fn.ts +486 -0
- package/src/index.ts +2 -0
- package/src/lib/updater.ts +1 -1
- package/test/unit/skills.test.ts +2 -2
package/skill-data/core/SKILL.md
CHANGED
|
@@ -9,10 +9,11 @@ allowed-tools: Bash(lizard:*), Bash(~/.lizard/bin/lizard:*), Bash(which:*), Bash
|
|
|
9
9
|
|
|
10
10
|
Lizard runs sandboxes and hosts apps, services, agents and managed databases. All capabilities are exposed through the `lizard` CLI (npm package `@lizard-build/cli`). This skill teaches you to drive it. If `lizard` isn't on PATH, install it: `curl -fsSL https://lizard.build/install.sh | bash` on macOS and Linux (no Node.js or sudo needed; if `lizard` is still not found, call `~/.lizard/bin/lizard`), `irm https://lizard.build/api/cli/install.ps1 | iex` in Windows PowerShell, or `npm install -g @lizard-build/cli` anywhere. The install script ends by running `lizard login`, so its output may already hold the sign-in links: see [Sign-in](#sign-in).
|
|
11
11
|
|
|
12
|
-
This guide covers the whole platform.
|
|
12
|
+
This guide covers the whole platform. Four references go deeper; read one only when the task needs that depth:
|
|
13
13
|
|
|
14
14
|
- `lizard skills get core --ref sandboxes --json`: templates, commands, files and ports in depth, lifetime, sizes, shell, coding agents in a sandbox, desktop (computer use), volumes, snapshots, fork and pause/resume.
|
|
15
15
|
- `lizard skills get core --ref deploys --json`: how builds are chosen, git and upload deploys, service fields, worker mode, secret precedence and scoping, addon variables, multi-step recipes.
|
|
16
|
+
- `lizard skills get core --ref functions --json`: Lizard Functions (AWS Lambda-compatible): `lizard fn deploy handler.py --packages requests --url` creates or updates a function with preinstalled libraries in one command; invoke, logs, schedules, Go/Rust, the AWS SDKs; recipes.
|
|
16
17
|
- `lizard skills get core --ref sdk --json`: building with Lizard from code through Lizard SDK (TypeScript, Python): sandboxes inside your own product, per-user workspaces and scoped keys, platform APIs.
|
|
17
18
|
|
|
18
19
|
If `$ARGUMENTS` is non-empty, treat it as the user's request and act on it. If empty, ask what they want to do on Lizard.
|
|
@@ -268,7 +269,12 @@ The loop: run `lizard gha --json` and act on `next`, then run it again. Repeat u
|
|
|
268
269
|
- `next.actor: "agent"`: do it yourself: run `next.command` (or, with no command, what `next.say` says, e.g. commit and push). If `next.confirm` is true, ask the user first (show `next.say`); it connects billing or edits their files.
|
|
269
270
|
- `verdict: "BLOCKED"`: tell the user `next.say` and stop; retrying won't help.
|
|
270
271
|
|
|
271
|
-
|
|
272
|
+
Migrating is just a YAML edit in the user's checkout: the CLI never opens a pull request or merges anything. Two ways, both fine:
|
|
273
|
+
|
|
274
|
+
- `lizard gha migrate` edits `runs-on` in `.github/workflows/*.yml` for you: it skips jobs that can't move (macOS, Windows, expressions, reusable workflows, runner groups), picks the size (`--size`, `--job build=large`) and keeps comments and formatting.
|
|
275
|
+
- Or edit `runs-on` yourself: replace `ubuntu-latest` / `ubuntu-24.04` / `ubuntu-22.04` with `lizard-medium-ubuntu-2404` (or `-small-` / `-large-`). Leave macOS and Windows jobs alone. Then run `lizard gha --json`: it checks the labels (a wrong one like `lizard-med-ubuntu-2404` comes back as `UNKNOWN_LABEL`).
|
|
276
|
+
|
|
277
|
+
Either way, show the user the diff, then commit and push the way the repository normally works (straight to the branch, or a pull request you open yourself). Don't change `runs-on` before `lizard gha` says READY: jobs would wait for a runner that can't start. Exit code is 0 whenever the state is known (also when not ready); `--require-ready` exits 1 unless ready.
|
|
272
278
|
|
|
273
279
|
## Response format
|
|
274
280
|
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Lizard Functions (AWS Lambda-compatible)
|
|
2
|
+
|
|
3
|
+
Functions run your handler on demand: an HTTP call, a schedule, a queue message or an SDK
|
|
4
|
+
`invoke`. They are AWS Lambda-compatible (same handler signatures, same API, boto3 / AWS SDK
|
|
5
|
+
/ AWS CLI work with a Lizard endpoint), run in `us-east-1` (alias `us`) and `eu-west-lim-a`
|
|
6
|
+
(alias `eu`), and have no 15-minute limit (up to 24 hours).
|
|
7
|
+
|
|
8
|
+
Use a function for: an API endpoint or webhook (`--url`), a cron job (`--schedule`), a
|
|
9
|
+
scraper or a data job you call from code, work queued from elsewhere. Use `lizard up` (a
|
|
10
|
+
service) instead for a long-running server or anything with its own process manager.
|
|
11
|
+
|
|
12
|
+
## One command: `lizard fn deploy`
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
lizard fn deploy handler.py --packages requests,beautifulsoup4 --url --json
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
It creates the function or updates it (same name = update), installs the packages, waits
|
|
19
|
+
until the function is ready and prints its ARN, URL and how to call it. It is idempotent: an
|
|
20
|
+
unchanged file and unchanged packages are a no-op (about 2 s), a code change about 4 s.
|
|
21
|
+
|
|
22
|
+
- **Source**: a file (`handler.py`, `index.mjs`, `lambda_function.rb`, `main.go`,
|
|
23
|
+
`bootstrap`), a directory, or `-` for stdin (with `--name` and `--runtime`).
|
|
24
|
+
- **Language and runtime**: from the file extension (Python 3.13, Node.js 22, Ruby 3.3) or
|
|
25
|
+
`--runtime` (`python3.9`-`3.13`, `nodejs18.x`-`24.x`, `ruby3.2`-`3.4`, `java11/17/21`,
|
|
26
|
+
`provided.al2023`). Go (`main.go` / `go.mod`) and Rust (`Cargo.toml`) are compiled on
|
|
27
|
+
Lizard into an Amazon Linux 2023 `bootstrap`. TypeScript: compile to `.js` first.
|
|
28
|
+
- **Handler**: found in the source (`def lambda_handler(event, context)` / `handler`,
|
|
29
|
+
`export const handler = async (event) => ...`); `--handler module.function` overrides.
|
|
30
|
+
- **Packages**:
|
|
31
|
+
- `--packages a,b==1.2` preinstalls libraries in the function's own layer (Node.js, Python,
|
|
32
|
+
Ruby): ready at every start, never reinstalled by code deploys, rebuilt only when the list
|
|
33
|
+
changes. `--packages ""` removes them.
|
|
34
|
+
- A `requirements.txt`, `package.json` (with dependencies) or `Gemfile` next to the file
|
|
35
|
+
or in the directory is installed into the code instead (each deploy rebuilds).
|
|
36
|
+
- For Go / Rust, `--packages` become `go get` / `cargo add` before the build.
|
|
37
|
+
- Packages are installed on Lizard on the runtime's own Amazon Linux image, so binary
|
|
38
|
+
wheels and native modules (numpy, pandas, Pillow, sharp, cryptography) match.
|
|
39
|
+
- **Settings**: `--env KEY=VALUE` (repeatable), `--memory <MB>` (up to 4096 on a 2 vCPU
|
|
40
|
+
sandbox, 8192 on 4, more on 8), `--timeout <s>`, `--region us|eu`, `--project <id>`.
|
|
41
|
+
- `--url` gives it a public HTTPS URL (the event is API Gateway v2 / function URL shaped:
|
|
42
|
+
`event["body"]`, `event["queryStringParameters"]`, `event["requestContext"]["http"]["method"]`;
|
|
43
|
+
return `{"statusCode": 200, "headers": {...}, "body": "..."}` or any JSON).
|
|
44
|
+
- `--schedule "rate(5 minutes)"` or `--schedule "cron(0 9 * * ? *)"` runs it on a schedule.
|
|
45
|
+
|
|
46
|
+
## Calling and watching
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
lizard fn invoke <name> '{"url": "https://example.com"}' --json # result (+ --logs)
|
|
50
|
+
lizard fn invoke <name> - < event.json
|
|
51
|
+
lizard fn invoke <name> '{}' --async # queued, returns at once
|
|
52
|
+
lizard fn logs <name> --since 10m [-f] # print() / console.log output
|
|
53
|
+
lizard fn ls --json # every region
|
|
54
|
+
lizard fn rm <name>
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`invoke` exits 1 when the handler raised (the error JSON is printed, with the log).
|
|
58
|
+
|
|
59
|
+
## From code (AWS SDKs)
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
eval "$(lizard fn env --region us)" # AWS_ACCESS_KEY_ID / SECRET / REGION / AWS_ENDPOINT_URL_LAMBDA ...
|
|
63
|
+
python3 -c "import boto3; print(boto3.client('lambda').invoke(FunctionName='scrape', Payload=b'{}')['Payload'].read())"
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The SDKs and the AWS CLI pick the endpoint up from `AWS_ENDPOINT_URL_LAMBDA` (also SQS,
|
|
67
|
+
EventBridge, Scheduler, CloudWatch Logs). One key works in every region (each region has its
|
|
68
|
+
own endpoint: `https://functions-<region>.onlizard.com`). Inside a function, the AWS SDK is
|
|
69
|
+
already pointed at Lizard (it can invoke other functions, send to SQS, read Lizard S3).
|
|
70
|
+
|
|
71
|
+
## Recipes
|
|
72
|
+
|
|
73
|
+
Scraper with a URL:
|
|
74
|
+
```python
|
|
75
|
+
# scrape.py — lizard fn deploy scrape.py --packages requests,beautifulsoup4 --url
|
|
76
|
+
import json, requests
|
|
77
|
+
from bs4 import BeautifulSoup
|
|
78
|
+
|
|
79
|
+
def handler(event, context):
|
|
80
|
+
url = (event.get("queryStringParameters") or {}).get("url") or event.get("url", "https://example.com")
|
|
81
|
+
html = requests.get(url, timeout=15).text
|
|
82
|
+
title = BeautifulSoup(html, "html.parser").title
|
|
83
|
+
return {"statusCode": 200, "body": json.dumps({"url": url, "title": title.string if title else None})}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Webhook (Node.js):
|
|
87
|
+
```js
|
|
88
|
+
// index.mjs — lizard fn deploy index.mjs --url
|
|
89
|
+
export const handler = async (event) => {
|
|
90
|
+
const body = JSON.parse(event.body || "{}");
|
|
91
|
+
return { statusCode: 200, body: JSON.stringify({ received: body }) };
|
|
92
|
+
};
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Cron job: `lizard fn deploy report.py --packages pandas --schedule "cron(0 8 * * ? *)" --env SLACK_URL=...`
|
|
96
|
+
|
|
97
|
+
Go: `lizard fn deploy main.go` with
|
|
98
|
+
```go
|
|
99
|
+
package main
|
|
100
|
+
import ("context"; "github.com/aws/aws-lambda-go/lambda")
|
|
101
|
+
func handler(ctx context.Context, e map[string]any) (map[string]any, error) { return map[string]any{"ok": true}, nil }
|
|
102
|
+
func main() { lambda.Start(handler) }
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Good to know
|
|
106
|
+
|
|
107
|
+
- The first function of a runtime in a region takes up to a minute (the runtime image is
|
|
108
|
+
pulled once); later ones start in seconds. Idle functions pause and resume in about a second.
|
|
109
|
+
- Calls keep working during deploys and package installs (no downtime; a call at the moment
|
|
110
|
+
of the switch can wait a second or two).
|
|
111
|
+
- Billing is the sandbox time the function's environments use (paused is free).
|
|
112
|
+
- The dashboard's Functions page shows the same functions (code editor, test, logs, packages).
|
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import * as zlib from "node:zlib";
|
|
4
|
+
import { createHash } from "node:crypto";
|
|
5
|
+
import chalk from "chalk";
|
|
6
|
+
import { Command } from "commander";
|
|
7
|
+
import { api, getBaseURL, getRequestToken, clientHeaders, APIError } from "../lib/api.js";
|
|
8
|
+
import { resolveProjectScope } from "../lib/resolve.js";
|
|
9
|
+
import { success, info, warn, fail, isJSONMode, printJSON, table } from "../lib/format.js";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* `lizard fn`: Lizard Functions (AWS Lambda-compatible) from the CLI, made for one-command
|
|
13
|
+
* use by people and agents: `lizard fn deploy handler.py --packages requests --url`
|
|
14
|
+
* creates or updates the function, installs its packages (kept in a layer: unchanged ones
|
|
15
|
+
* are not reinstalled), waits until it is ready and prints how to call it.
|
|
16
|
+
* Everything goes through the platform as the logged-in user (no AWS keys needed);
|
|
17
|
+
* `lizard fn env` prints keys for the AWS SDKs / CLI when code needs them.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
// ---------------- detection ----------------
|
|
21
|
+
export type Lang = "python" | "node" | "ruby" | "go" | "rust" | "shell";
|
|
22
|
+
export const DEFAULT_RUNTIME: Record<Lang, string> = {
|
|
23
|
+
python: "python3.13", node: "nodejs22.x", ruby: "ruby3.3", go: "provided.al2023", rust: "provided.al2023", shell: "provided.al2023",
|
|
24
|
+
};
|
|
25
|
+
const SKIP_DIRS = new Set([".git", "node_modules", "__pycache__", ".venv", "venv", "target", ".lizard", "dist-lizard"]);
|
|
26
|
+
|
|
27
|
+
export interface Source { lang: Lang; files: { name: string; data: Buffer; mode?: number }[]; handler: string; entry: string; deps: boolean }
|
|
28
|
+
|
|
29
|
+
/** What a file or directory is: language, files to send, handler, and whether it has a dependency file. */
|
|
30
|
+
export function detectSource(p: string, opts: { runtime?: string; handler?: string; stdinName?: string; stdin?: string } = {}): Source {
|
|
31
|
+
let files: Source["files"] = [];
|
|
32
|
+
let entry: string;
|
|
33
|
+
if (opts.stdin !== undefined) {
|
|
34
|
+
entry = opts.stdinName || defaultFileFor(langOfRuntime(opts.runtime) ?? "python");
|
|
35
|
+
files = [{ name: entry, data: Buffer.from(opts.stdin) }];
|
|
36
|
+
} else {
|
|
37
|
+
const st = fs.statSync(p);
|
|
38
|
+
if (st.isDirectory()) {
|
|
39
|
+
files = walk(p);
|
|
40
|
+
entry = pickEntry(files.map((f) => f.name));
|
|
41
|
+
} else {
|
|
42
|
+
entry = path.basename(p);
|
|
43
|
+
files = [{ name: entry, data: fs.readFileSync(p), mode: st.mode & 0o111 ? 0o100755 : undefined }];
|
|
44
|
+
// A dependency file next to a single file is part of the function.
|
|
45
|
+
for (const dep of ["requirements.txt", "package.json", "Gemfile", "go.mod", "go.sum"]) {
|
|
46
|
+
const dp = path.join(path.dirname(p), dep);
|
|
47
|
+
if (fs.existsSync(dp)) files.push({ name: dep, data: fs.readFileSync(dp) });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const names = files.map((f) => f.name);
|
|
52
|
+
const lang: Lang = langOfRuntime(opts.runtime) ?? (names.includes("Cargo.toml") ? "rust" : names.includes("go.mod") || entry.endsWith(".go") ? "go"
|
|
53
|
+
: /\.py$/.test(entry) ? "python" : /\.(m?js|cjs)$/.test(entry) ? "node" : /\.rb$/.test(entry) ? "ruby" : entry === "bootstrap" ? "shell"
|
|
54
|
+
: /\.ts$/.test(entry) ? (fail("TypeScript: compile it to .js first (e.g. npx esbuild index.ts --bundle --platform=node --outfile=index.mjs), then deploy the .js", 2), "node")
|
|
55
|
+
: (fail(`Can't tell the language of ${entry}: pass --runtime (e.g. python3.13, nodejs22.x, ruby3.3, provided.al2023)`, 2), "python"));
|
|
56
|
+
const text = files.find((f) => f.name === entry)?.data.toString("utf8") ?? "";
|
|
57
|
+
const handler = opts.handler ?? (lang === "go" || lang === "rust" || lang === "shell" ? "bootstrap" : findHandler(lang, entry, text));
|
|
58
|
+
const deps = names.some((n) => ["requirements.txt", "Gemfile", "go.mod", "Cargo.toml"].includes(n))
|
|
59
|
+
|| (names.includes("package.json") && hasNodeDeps(files.find((f) => f.name === "package.json")!.data));
|
|
60
|
+
return { lang, files, handler, entry, deps };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function langOfRuntime(rt?: string): Lang | null {
|
|
64
|
+
if (!rt) return null;
|
|
65
|
+
if (/^python/.test(rt)) return "python";
|
|
66
|
+
if (/^nodejs/.test(rt)) return "node";
|
|
67
|
+
if (/^ruby/.test(rt)) return "ruby";
|
|
68
|
+
if (rt === "go" || rt === "go1.x") return "go";
|
|
69
|
+
if (rt === "rust") return "rust";
|
|
70
|
+
if (/^provided/.test(rt)) return null; // decided by the files
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
const defaultFileFor = (l: Lang) => ({ python: "lambda_function.py", node: "index.mjs", ruby: "lambda_function.rb", go: "main.go", rust: "src/main.rs", shell: "bootstrap" }[l]);
|
|
74
|
+
|
|
75
|
+
function walk(root: string, rel = ""): Source["files"] {
|
|
76
|
+
const out: Source["files"] = [];
|
|
77
|
+
for (const e of fs.readdirSync(path.join(root, rel), { withFileTypes: true })) {
|
|
78
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
79
|
+
if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name) && !e.name.startsWith(".")) out.push(...walk(root, r)); continue; }
|
|
80
|
+
if (!e.isFile() || e.name === ".DS_Store") continue;
|
|
81
|
+
const st = fs.statSync(path.join(root, r));
|
|
82
|
+
out.push({ name: r, data: fs.readFileSync(path.join(root, r)), mode: st.mode & 0o111 ? 0o100755 : undefined });
|
|
83
|
+
}
|
|
84
|
+
const size = out.reduce((n, f) => n + f.data.length, 0);
|
|
85
|
+
if (size > 50 * 1024 * 1024) fail(`${root} is ${Math.round(size / 1048576)} MB; a function's source is at most 50 MB (dependencies are installed by Lizard: don't ship node_modules or venv)`, 2);
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function pickEntry(names: string[]): string {
|
|
90
|
+
for (const n of ["Cargo.toml", "go.mod", "lambda_function.py", "handler.py", "app.py", "main.py", "index.mjs", "index.js", "handler.mjs", "handler.js", "app.js", "lambda_function.rb", "handler.rb", "bootstrap"]) {
|
|
91
|
+
if (names.includes(n)) return n === "Cargo.toml" ? "src/main.rs" : n === "go.mod" ? (names.find((x) => !x.includes("/") && x.endsWith(".go")) ?? "main.go") : n;
|
|
92
|
+
}
|
|
93
|
+
const top = names.filter((n) => !n.includes("/"));
|
|
94
|
+
const guess = top.find((n) => /\.(py|m?js|cjs|rb|go)$/.test(n));
|
|
95
|
+
if (!guess) fail("No function file found: name it handler.py, index.mjs, lambda_function.rb, main.go (or pass a file)", 2);
|
|
96
|
+
return guess!;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The handler (module.function) from the source, as Lambda names it. */
|
|
100
|
+
export function findHandler(lang: Lang, entry: string, text: string): string {
|
|
101
|
+
const mod = entry.replace(/\.(py|m?js|cjs|rb)$/, "");
|
|
102
|
+
if (lang === "python") {
|
|
103
|
+
const names = [...text.matchAll(/^(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)/gm)].map((m) => m[1]);
|
|
104
|
+
const fn = ["lambda_handler", "handler", "main"].find((n) => names.includes(n)) ?? names[0] ?? "lambda_handler";
|
|
105
|
+
return `${mod}.${fn}`;
|
|
106
|
+
}
|
|
107
|
+
if (lang === "node") {
|
|
108
|
+
const exported = [...text.matchAll(/export\s+(?:const|let|var|async\s+function|function)\s+([A-Za-z_$][\w$]*)/g), ...text.matchAll(/(?:module\.)?exports\.([A-Za-z_$][\w$]*)\s*=/g)].map((m) => m[1]);
|
|
109
|
+
const fn = ["handler", "lambdaHandler", "main"].find((n) => exported.includes(n)) ?? exported[0] ?? "handler";
|
|
110
|
+
return `${mod}.${fn}`;
|
|
111
|
+
}
|
|
112
|
+
if (lang === "ruby") {
|
|
113
|
+
const names = [...text.matchAll(/^def\s+([a-z_]\w*)/gm)].map((m) => m[1]);
|
|
114
|
+
return `${mod}.${["lambda_handler", "handler"].find((n) => names.includes(n)) ?? names[0] ?? "lambda_handler"}`;
|
|
115
|
+
}
|
|
116
|
+
return "bootstrap";
|
|
117
|
+
}
|
|
118
|
+
function hasNodeDeps(pkg: Buffer): boolean {
|
|
119
|
+
try { return Object.keys(JSON.parse(pkg.toString("utf8")).dependencies ?? {}).length > 0; } catch { return false; }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---------------- zip (no dependency) ----------------
|
|
123
|
+
const CRC = (() => { const t = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } return t; })();
|
|
124
|
+
const crc32 = (b: Buffer) => { let c = 0xffffffff; for (let i = 0; i < b.length; i++) c = CRC[(c ^ b[i]) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
|
|
125
|
+
export function zipFiles(files: Source["files"]): Buffer {
|
|
126
|
+
const parts: Buffer[] = [], central: Buffer[] = [];
|
|
127
|
+
let off = 0;
|
|
128
|
+
for (const f of files) {
|
|
129
|
+
const name = Buffer.from(f.name), comp = zlib.deflateRawSync(f.data), crc = crc32(f.data);
|
|
130
|
+
const lh = Buffer.alloc(30);
|
|
131
|
+
lh.writeUInt32LE(0x04034b50, 0); lh.writeUInt16LE(20, 4); lh.writeUInt16LE(8, 8); lh.writeUInt16LE(0x21, 12);
|
|
132
|
+
lh.writeUInt32LE(crc, 14); lh.writeUInt32LE(comp.length, 18); lh.writeUInt32LE(f.data.length, 22); lh.writeUInt16LE(name.length, 26);
|
|
133
|
+
parts.push(lh, name, comp);
|
|
134
|
+
const ch = Buffer.alloc(46);
|
|
135
|
+
ch.writeUInt32LE(0x02014b50, 0); ch.writeUInt16LE(0x0314, 4); ch.writeUInt16LE(20, 6); ch.writeUInt16LE(8, 10); ch.writeUInt16LE(0x21, 14);
|
|
136
|
+
ch.writeUInt32LE(crc, 16); ch.writeUInt32LE(comp.length, 20); ch.writeUInt32LE(f.data.length, 24); ch.writeUInt16LE(name.length, 28);
|
|
137
|
+
ch.writeUInt32LE((((f.mode ?? (f.name === "bootstrap" ? 0o100755 : 0o100644)) << 16) >>> 0), 38); ch.writeUInt32LE(off, 42);
|
|
138
|
+
central.push(ch, name);
|
|
139
|
+
off += 30 + name.length + comp.length;
|
|
140
|
+
}
|
|
141
|
+
const cd = Buffer.concat(central), end = Buffer.alloc(22);
|
|
142
|
+
end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10); end.writeUInt32LE(cd.length, 12); end.writeUInt32LE(off, 16);
|
|
143
|
+
return Buffer.concat([...parts, cd, end]);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---------------- platform calls ----------------
|
|
147
|
+
interface Account { accountId: string; region: string; endpoint: string }
|
|
148
|
+
const REGION_ALIASES: Record<string, string> = { us: "us-east-1", "us-east": "us-east-1", eu: "eu-west-lim-a", "eu-west": "eu-west-lim-a" };
|
|
149
|
+
|
|
150
|
+
async function regions(): Promise<string[]> {
|
|
151
|
+
const r = await api.get<any>("/api/functions/regions").catch(() => null);
|
|
152
|
+
const list: string[] = (Array.isArray(r) ? r : r?.regions ?? []).map((x: any) => (typeof x === "string" ? x : x.region ?? x.id)).filter(Boolean);
|
|
153
|
+
return list.filter((x) => !x.startsWith("canary"));
|
|
154
|
+
}
|
|
155
|
+
async function resolveRegion(flag?: string): Promise<string> {
|
|
156
|
+
const all = await regions();
|
|
157
|
+
if (!flag) return all.includes("us-east-1") ? "us-east-1" : all[0] ?? "us-east-1";
|
|
158
|
+
const r = REGION_ALIASES[flag] ?? flag;
|
|
159
|
+
if (all.length && !all.includes(r)) fail(`Lizard Functions runs in ${all.join(", ")} (aliases: us, eu); not in ${flag}`, 2);
|
|
160
|
+
return r;
|
|
161
|
+
}
|
|
162
|
+
async function accounts(projectId: string): Promise<Account[]> {
|
|
163
|
+
return api.get<Account[]>(`/api/functions/accounts?projectId=${encodeURIComponent(projectId)}`);
|
|
164
|
+
}
|
|
165
|
+
async function accountFor(projectId: string, region: string, create: boolean): Promise<Account | null> {
|
|
166
|
+
const a = (await accounts(projectId)).find((x) => x.region === region);
|
|
167
|
+
if (a || !create) return a ?? null;
|
|
168
|
+
return api.post<Account>("/api/functions/accounts", { projectId, region, withKey: false });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** One AWS API call as the account, through the platform (no AWS keys on this machine). */
|
|
172
|
+
async function aws<T = any>(acct: Account, method: string, p: string, body?: unknown, opts: { target?: string; headers?: Record<string, string> } = {}): Promise<{ data: T; headers: Headers; status: number }> {
|
|
173
|
+
const headers: Record<string, string> = { ...clientHeaders(), ...(opts.headers ?? {}) };
|
|
174
|
+
const tok = getRequestToken();
|
|
175
|
+
if (tok) headers.authorization = `Bearer ${tok}`;
|
|
176
|
+
if (body !== undefined) headers["content-type"] = "application/json";
|
|
177
|
+
if (opts.target) headers["x-lizard-target"] = opts.target;
|
|
178
|
+
const res = await fetch(`${getBaseURL()}/api/functions/accounts/${acct.accountId}/aws/${p.replace(/^\//, "")}`, {
|
|
179
|
+
method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(900_000),
|
|
180
|
+
});
|
|
181
|
+
const text = await res.text();
|
|
182
|
+
let data: any = undefined;
|
|
183
|
+
if (text) { try { data = JSON.parse(text); } catch { data = text; } }
|
|
184
|
+
if (!res.ok) {
|
|
185
|
+
const msg = (data && (data.message || data.Message || data.error)) || text || res.statusText;
|
|
186
|
+
throw new APIError(res.status, String(msg), String(data?.__type ?? data?.Type ?? ""), data);
|
|
187
|
+
}
|
|
188
|
+
return { data, headers: res.headers, status: res.status };
|
|
189
|
+
}
|
|
190
|
+
const fnPath = (name: string) => `2015-03-31/functions/${encodeURIComponent(name)}`;
|
|
191
|
+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
192
|
+
|
|
193
|
+
async function getFn(acct: Account, name: string): Promise<any | null> {
|
|
194
|
+
try { return (await aws(acct, "GET", fnPath(name))).data; }
|
|
195
|
+
catch (e) { if (e instanceof APIError && e.status === 404) return null; throw e; }
|
|
196
|
+
}
|
|
197
|
+
async function waitReady(acct: Account, name: string, limitMs = 15 * 60_000, onTick?: (c: any) => void): Promise<any> {
|
|
198
|
+
const end = Date.now() + limitMs;
|
|
199
|
+
for (;;) {
|
|
200
|
+
const f = (await getFn(acct, name))?.Configuration;
|
|
201
|
+
if (f) {
|
|
202
|
+
onTick?.(f);
|
|
203
|
+
if (f.State === "Failed") throw new Error(f.StateReason || "the function failed to start");
|
|
204
|
+
if (f.LastUpdateStatus === "Failed") throw new Error(f.LastUpdateStatusReason || "the update failed");
|
|
205
|
+
if (f.State === "Active" && f.LastUpdateStatus !== "InProgress") return f;
|
|
206
|
+
}
|
|
207
|
+
if (Date.now() > end) throw new Error("timed out waiting for the function");
|
|
208
|
+
await sleep(400);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
async function waitBuild(acct: Account, id: string, spinner: (s: string) => void): Promise<any> {
|
|
212
|
+
const t0 = Date.now();
|
|
213
|
+
for (;;) {
|
|
214
|
+
const b = (await aws(acct, "GET", `lizard/builds/${id}`)).data;
|
|
215
|
+
if (b.Status !== "InProgress") return b;
|
|
216
|
+
spinner(`${b.Kind === "layer" ? "installing packages" : `building (${b.Language})`}… ${Math.round((Date.now() - t0) / 1000)}s`);
|
|
217
|
+
await sleep(1000);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
function parseEnv(list: string[] | undefined): Record<string, string> | undefined {
|
|
221
|
+
if (!list?.length) return undefined;
|
|
222
|
+
const out: Record<string, string> = {};
|
|
223
|
+
for (const kv of list) { const i = kv.indexOf("="); if (i < 1) fail(`--env takes KEY=VALUE (got ${kv})`, 2); out[kv.slice(0, i)] = kv.slice(i + 1); }
|
|
224
|
+
return out;
|
|
225
|
+
}
|
|
226
|
+
const splitList = (v?: string[] | string) => (Array.isArray(v) ? v : v ? [v] : []).flatMap((x) => x.split(/[,\s]+/)).map((x) => x.trim()).filter(Boolean);
|
|
227
|
+
|
|
228
|
+
const DEBUG = !!process.env.LIZARD_DEBUG_FN;
|
|
229
|
+
let tStart = Date.now();
|
|
230
|
+
function status(msg: string) {
|
|
231
|
+
if (DEBUG) process.stderr.write(`[${((Date.now() - tStart) / 1000).toFixed(2)}s] ${msg}\n`); if (!isJSONMode() && process.stderr.isTTY) process.stderr.write(`\r\x1b[2K${chalk.dim(msg)}`); }
|
|
232
|
+
function statusDone() { if (!isJSONMode() && process.stderr.isTTY) process.stderr.write("\r\x1b[2K"); }
|
|
233
|
+
|
|
234
|
+
// ---------------- commands ----------------
|
|
235
|
+
export function registerFn(program: Command) {
|
|
236
|
+
const fn = program.command("fn").alias("functions")
|
|
237
|
+
.description("Lizard Functions (AWS Lambda-compatible): deploy, invoke, logs")
|
|
238
|
+
.addHelpText("after", `
|
|
239
|
+
Examples:
|
|
240
|
+
lizard fn deploy handler.py --packages requests # create or update, install, wait, done
|
|
241
|
+
lizard fn deploy ./scraper --url # a directory (requirements.txt / package.json / go.mod / Cargo.toml)
|
|
242
|
+
echo 'def handler(e, c): return e' | lizard fn deploy - --name echo --runtime python3.13
|
|
243
|
+
lizard fn deploy main.go --schedule "rate(5 minutes)" # Go and Rust are compiled on Lizard
|
|
244
|
+
lizard fn invoke scraper '{"url": "https://example.com"}'
|
|
245
|
+
lizard fn logs scraper --since 10m
|
|
246
|
+
lizard fn ls
|
|
247
|
+
eval "$(lizard fn env)" # AWS SDK / CLI credentials and endpoint`);
|
|
248
|
+
|
|
249
|
+
fn.command("deploy")
|
|
250
|
+
.description("Create or update a function from a file, a directory or stdin (-); installs packages, waits until it is ready")
|
|
251
|
+
.argument("[path]", "file, directory or - for stdin", ".")
|
|
252
|
+
.option("--name <name>", "function name (default: from the file or directory)")
|
|
253
|
+
.option("--runtime <runtime>", "e.g. python3.13, nodejs22.x, ruby3.3, provided.al2023 (default: from the source)")
|
|
254
|
+
.option("--handler <handler>", "e.g. app.handler (default: found in the source)")
|
|
255
|
+
.option("--packages <list...>", "libraries to preinstall, e.g. requests numpy==2.1.3 (comma or space separated)")
|
|
256
|
+
.option("--env <KEY=VALUE...>", "environment variables")
|
|
257
|
+
.option("--memory <mb>", "memory in MB", (v) => parseInt(v, 10))
|
|
258
|
+
.option("--timeout <seconds>", "timeout in seconds", (v) => parseInt(v, 10))
|
|
259
|
+
.option("--url", "give it a public HTTPS URL")
|
|
260
|
+
.option("--schedule <expression>", 'run it on a schedule: "rate(5 minutes)" or "cron(0 9 * * ? *)"')
|
|
261
|
+
.option("--region <region>", "us-east-1 (us) or eu-west-lim-a (eu)")
|
|
262
|
+
.option("--project <id>", "project (default: the linked one)")
|
|
263
|
+
.action(async (p: string, o: any) => {
|
|
264
|
+
const t0 = Date.now(); tStart = t0;
|
|
265
|
+
const stdin = p === "-" ? fs.readFileSync(0, "utf8") : undefined;
|
|
266
|
+
if (p !== "-" && !fs.existsSync(p)) fail(`${p} does not exist`, 2);
|
|
267
|
+
if (stdin !== undefined && !o.name) fail("--name is required with stdin", 2);
|
|
268
|
+
const src = detectSource(p, { runtime: o.runtime, handler: o.handler, stdin });
|
|
269
|
+
const name: string = o.name ?? defaultName(p, src);
|
|
270
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) fail(`Function name ${name}: letters, numbers, hyphens and underscores, up to 64 (pass --name)`, 2);
|
|
271
|
+
const runtime = o.runtime && !/^(go|rust)$/.test(o.runtime) ? o.runtime : DEFAULT_RUNTIME[src.lang];
|
|
272
|
+
const packages = splitList(o.packages);
|
|
273
|
+
const { projectId } = await resolveProjectScope(o.project);
|
|
274
|
+
const region = await resolveRegion(o.region);
|
|
275
|
+
status(`account in ${region}…`);
|
|
276
|
+
const acct = (await accountFor(projectId, region, true))!;
|
|
277
|
+
const zipBuf = zipFiles(src.files);
|
|
278
|
+
const zip = zipBuf.toString("base64");
|
|
279
|
+
const zipSha = createHash("sha256").update(zipBuf).digest("base64");
|
|
280
|
+
const config: Record<string, unknown> = { Runtime: runtime, Handler: src.handler };
|
|
281
|
+
if (o.memory) config.MemorySize = o.memory;
|
|
282
|
+
if (o.timeout) config.Timeout = o.timeout;
|
|
283
|
+
const env = parseEnv(o.env);
|
|
284
|
+
if (env) config.Environment = { Variables: env };
|
|
285
|
+
const existing = await getFn(acct, name);
|
|
286
|
+
const compiled = src.lang === "go" || src.lang === "rust";
|
|
287
|
+
let created = false;
|
|
288
|
+
|
|
289
|
+
// Code: built on Lizard when it has a dependency file (or is Go / Rust), else sent as is.
|
|
290
|
+
if (src.deps || compiled) {
|
|
291
|
+
status(existing ? "building…" : "creating (building)…");
|
|
292
|
+
if (existing) await waitReady(acct, name);
|
|
293
|
+
if (existing) await aws(acct, "PUT", `${fnPath(name)}/configuration`, config);
|
|
294
|
+
if (existing) await waitReady(acct, name);
|
|
295
|
+
const job = (await aws(acct, "POST", `lizard/functions/${encodeURIComponent(name)}/build`, {
|
|
296
|
+
ZipFile: zip, Runtime: runtime, ...(compiled && packages.length ? { Packages: packages } : {}),
|
|
297
|
+
...(existing ? {} : { Create: { Role: "arn:aws:iam::000000000000:role/lizard-function", MemorySize: 512, Timeout: 30, ...config } }),
|
|
298
|
+
})).data;
|
|
299
|
+
const b = await waitBuild(acct, job.BuildId, status);
|
|
300
|
+
if (b.Status !== "Succeeded") { statusDone(); fail(`Build failed: ${b.Error}\n${String(b.Log || "").slice(-3000)}`, 1, "BUILD_FAILED"); }
|
|
301
|
+
created = !existing;
|
|
302
|
+
} else if (existing) {
|
|
303
|
+
// Only what changed is sent: the same code (by SHA-256) and the same settings are no-ops.
|
|
304
|
+
const c = existing.Configuration ?? {};
|
|
305
|
+
if (c.LastUpdateStatus === "InProgress") await waitReady(acct, name);
|
|
306
|
+
if (c.CodeSha256 !== zipSha) {
|
|
307
|
+
status("updating code…");
|
|
308
|
+
await aws(acct, "PUT", `${fnPath(name)}/code`, { ZipFile: zip });
|
|
309
|
+
}
|
|
310
|
+
const changed = Object.entries(config).some(([k, v]) => JSON.stringify(k === "Environment" ? { Variables: c.Environment?.Variables ?? {} } : c[k]) !== JSON.stringify(v));
|
|
311
|
+
if (changed) {
|
|
312
|
+
status("updating settings…");
|
|
313
|
+
await waitReady(acct, name);
|
|
314
|
+
await aws(acct, "PUT", `${fnPath(name)}/configuration`, config);
|
|
315
|
+
}
|
|
316
|
+
} else {
|
|
317
|
+
status("creating…");
|
|
318
|
+
await aws(acct, "POST", "2015-03-31/functions", { FunctionName: name, Role: "arn:aws:iam::000000000000:role/lizard-function", MemorySize: 512, Timeout: 30, ...config, Code: { ZipFile: zip } });
|
|
319
|
+
created = true;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Packages (Node.js / Python / Ruby): the function's own layer, rebuilt only when the list changes.
|
|
323
|
+
let installed: string[] | null = null;
|
|
324
|
+
if (!compiled) {
|
|
325
|
+
await waitReady(acct, name, 15 * 60_000, (c) => status(c.State === "Pending" ? "preparing the runtime (the first one in a region takes up to a minute)…" : "updating…"));
|
|
326
|
+
const cur = (await aws(acct, "GET", `lizard/functions/${encodeURIComponent(name)}/packages`)).data;
|
|
327
|
+
const same = JSON.stringify([...(cur.Packages ?? [])].sort()) === JSON.stringify([...packages].sort());
|
|
328
|
+
if (o.packages !== undefined && !same) {
|
|
329
|
+
status("installing packages…");
|
|
330
|
+
const job = (await aws(acct, "PUT", `lizard/functions/${encodeURIComponent(name)}/packages`, { Packages: packages })).data;
|
|
331
|
+
if (job.BuildId) {
|
|
332
|
+
const b = await waitBuild(acct, job.BuildId, status);
|
|
333
|
+
if (b.Status !== "Succeeded") { statusDone(); fail(`Installing packages failed: ${b.Error}\n${String(b.Log || "").slice(-3000)}`, 1, "BUILD_FAILED"); }
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
installed = o.packages !== undefined ? packages : cur.Packages ?? [];
|
|
337
|
+
}
|
|
338
|
+
const cfg = await waitReady(acct, name, 15 * 60_000, (c) => status(c.State === "Pending" ? "preparing the runtime (the first one in a region takes up to a minute)…" : "starting…"));
|
|
339
|
+
|
|
340
|
+
// URL and schedule.
|
|
341
|
+
let url: string | null = null;
|
|
342
|
+
if (o.url) {
|
|
343
|
+
try { url = (await aws(acct, "GET", `2021-10-31/functions/${encodeURIComponent(name)}/url`)).data.FunctionUrl; }
|
|
344
|
+
catch (e) {
|
|
345
|
+
if (!(e instanceof APIError && e.status === 404)) throw e;
|
|
346
|
+
url = (await aws(acct, "POST", `2021-10-31/functions/${encodeURIComponent(name)}/url`, { AuthType: "NONE", Cors: { AllowOrigins: ["*"] } })).data.FunctionUrl;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (o.schedule) {
|
|
350
|
+
const body = { ScheduleExpression: o.schedule, FlexibleTimeWindow: { Mode: "OFF" }, Target: { Arn: cfg.FunctionArn, RoleArn: "arn:aws:iam::000000000000:role/lizard-scheduler" }, State: "ENABLED" };
|
|
351
|
+
try { await aws(acct, "PUT", `schedules/${encodeURIComponent(name)}`, body); }
|
|
352
|
+
catch (e) { if (e instanceof APIError && e.status === 404) await aws(acct, "POST", `schedules/${encodeURIComponent(name)}`, body); else throw e; }
|
|
353
|
+
}
|
|
354
|
+
statusDone();
|
|
355
|
+
const secs = ((Date.now() - t0) / 1000).toFixed(1);
|
|
356
|
+
const out = { name, region, created, runtime: cfg.Runtime, handler: cfg.Handler, language: src.lang, arn: cfg.FunctionArn, packages: installed, url, schedule: o.schedule ?? null,
|
|
357
|
+
seconds: Number(secs), invoke: `lizard fn invoke ${name}${o.region ? ` --region ${region}` : ""} '{}'` };
|
|
358
|
+
if (isJSONMode()) return printJSON(out);
|
|
359
|
+
success(`${created ? "Created" : "Updated"} ${chalk.bold(name)} in ${region} (${cfg.Runtime}, ${cfg.Handler}) in ${secs}s`);
|
|
360
|
+
if (installed?.length) info(`Packages: ${installed.join(" ")}`);
|
|
361
|
+
if (url) info(`URL: ${chalk.cyan(url)}`);
|
|
362
|
+
if (o.schedule) info(`Schedule: ${o.schedule}`);
|
|
363
|
+
info(`Call it: ${chalk.cyan(out.invoke)}`);
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
fn.command("invoke")
|
|
367
|
+
.description("Call a function and print its result (and its log with --logs)")
|
|
368
|
+
.argument("<name>")
|
|
369
|
+
.argument("[event]", "event JSON (default {}; - reads stdin)", "{}")
|
|
370
|
+
.option("--logs", "print the invocation's log")
|
|
371
|
+
.option("--async", "queue it (InvocationType Event) and return at once")
|
|
372
|
+
.option("--region <region>").option("--project <id>")
|
|
373
|
+
.action(async (name: string, event: string, o: any) => {
|
|
374
|
+
const acct = await existingAccount(o, name);
|
|
375
|
+
const body = event === "-" ? fs.readFileSync(0, "utf8") : event;
|
|
376
|
+
let parsed: unknown;
|
|
377
|
+
try { parsed = JSON.parse(body); } catch { fail("The event must be JSON", 2); }
|
|
378
|
+
const r = await aws(acct, "POST", `${fnPath(name)}/invocations`, parsed, { headers: { "x-amz-log-type": "Tail", ...(o.async ? { "x-amz-invocation-type": "Event" } : {}) } });
|
|
379
|
+
const err = r.headers.get("x-amz-function-error");
|
|
380
|
+
const tail = r.headers.get("x-amz-log-result");
|
|
381
|
+
const logs = tail ? Buffer.from(tail, "base64").toString("utf8") : "";
|
|
382
|
+
if (isJSONMode()) { if (err) process.exitCode = 1; return printJSON({ status: o.async ? "queued" : err ? "error" : "ok", error: err || undefined, result: r.data ?? null, logs: o.logs ? logs : undefined }); }
|
|
383
|
+
if (o.logs && logs) process.stderr.write(chalk.dim(logs.endsWith("\n") ? logs : logs + "\n"));
|
|
384
|
+
if (o.async) return success("Queued");
|
|
385
|
+
process.stdout.write((typeof r.data === "string" ? r.data : JSON.stringify(r.data ?? null, null, 2)) + "\n");
|
|
386
|
+
if (err) { process.stderr.write(chalk.red(`Function error (${err})\n`)); if (!o.logs && logs) process.stderr.write(chalk.dim(logs)); process.exitCode = 1; }
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
fn.command("logs")
|
|
390
|
+
.description("A function's logs (CloudWatch Logs format)")
|
|
391
|
+
.argument("<name>")
|
|
392
|
+
.option("--since <duration>", "e.g. 10m, 2h, 1d", "1h")
|
|
393
|
+
.option("-f, --follow", "keep printing new lines")
|
|
394
|
+
.option("--region <region>").option("--project <id>")
|
|
395
|
+
.action(async (name: string, o: any) => {
|
|
396
|
+
const acct = await existingAccount(o, name);
|
|
397
|
+
let start = Date.now() - parseDuration(o.since);
|
|
398
|
+
const seen = new Set<string>();
|
|
399
|
+
for (;;) {
|
|
400
|
+
const r = await aws<any>(acct, "POST", "", { logGroupName: `/aws/lambda/${name}`, startTime: start, limit: 1000 }, { target: "Logs_20140328.FilterLogEvents" }).catch((e) => {
|
|
401
|
+
if (e instanceof APIError && (e.status === 400 || e.status === 404)) return { data: { events: [] } }; throw e; });
|
|
402
|
+
const events = (r.data.events ?? []).filter((e: any) => !seen.has(e.eventId ?? `${e.timestamp}${e.message}`));
|
|
403
|
+
if (isJSONMode() && !o.follow) return printJSON(events);
|
|
404
|
+
for (const e of events) {
|
|
405
|
+
seen.add(e.eventId ?? `${e.timestamp}${e.message}`);
|
|
406
|
+
if (isJSONMode()) printJSON(e);
|
|
407
|
+
else process.stdout.write(`${chalk.dim(new Date(e.timestamp).toISOString())} ${e.message}${String(e.message).endsWith("\n") ? "" : "\n"}`);
|
|
408
|
+
start = Math.max(start, e.timestamp);
|
|
409
|
+
}
|
|
410
|
+
if (!o.follow) return;
|
|
411
|
+
await sleep(2000);
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
fn.command("ls").alias("list")
|
|
416
|
+
.description("Functions of the project, in every region")
|
|
417
|
+
.option("--project <id>")
|
|
418
|
+
.action(async (o: any) => {
|
|
419
|
+
const { projectId } = await resolveProjectScope(o.project);
|
|
420
|
+
const rows: any[] = [];
|
|
421
|
+
for (const a of await accounts(projectId)) {
|
|
422
|
+
const r = await aws<any>(a, "GET", "2015-03-31/functions/?MaxItems=200").catch(() => ({ data: { Functions: [] } }));
|
|
423
|
+
for (const f of r.data.Functions ?? []) rows.push({ name: f.FunctionName, region: a.region, runtime: f.Runtime ?? f.PackageType, state: f.State ?? "Active", memory: f.MemorySize, modified: f.LastModified });
|
|
424
|
+
}
|
|
425
|
+
if (isJSONMode()) return printJSON(rows);
|
|
426
|
+
if (!rows.length) return info("No functions yet: lizard fn deploy handler.py");
|
|
427
|
+
table(["NAME", "REGION", "RUNTIME", "STATE", "MEMORY", "MODIFIED"], rows.map((r) => [r.name, r.region, r.runtime, r.state, `${r.memory} MB`, String(r.modified).slice(0, 19)]));
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
fn.command("rm").alias("delete")
|
|
431
|
+
.description("Delete a function (and its schedule)")
|
|
432
|
+
.argument("<name>")
|
|
433
|
+
.option("--region <region>").option("--project <id>")
|
|
434
|
+
.action(async (name: string, o: any) => {
|
|
435
|
+
const acct = await existingAccount(o, name);
|
|
436
|
+
await aws(acct, "DELETE", `schedules/${encodeURIComponent(name)}`).catch(() => {});
|
|
437
|
+
await aws(acct, "DELETE", fnPath(name));
|
|
438
|
+
if (isJSONMode()) return printJSON({ deleted: name, region: acct.region });
|
|
439
|
+
success(`Deleted ${name} (${acct.region})`);
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
fn.command("env")
|
|
443
|
+
.description("Print AWS credentials and endpoints for the project's functions (for the AWS SDKs / CLI): eval \"$(lizard fn env)\"")
|
|
444
|
+
.option("--region <region>").option("--project <id>")
|
|
445
|
+
.action(async (o: any) => {
|
|
446
|
+
const { projectId } = await resolveProjectScope(o.project);
|
|
447
|
+
const region = await resolveRegion(o.region);
|
|
448
|
+
await accountFor(projectId, region, true);
|
|
449
|
+
const k = await api.post<any>(`/api/functions/projects/${encodeURIComponent(projectId)}/keys`);
|
|
450
|
+
const ep = k.endpoints?.[region];
|
|
451
|
+
if (isJSONMode()) return printJSON({ AWS_ACCESS_KEY_ID: k.accessKeyId, AWS_SECRET_ACCESS_KEY: k.secretAccessKey, AWS_REGION: region, AWS_ENDPOINT_URL_LAMBDA: ep, endpoints: k.endpoints });
|
|
452
|
+
process.stdout.write([`export AWS_ACCESS_KEY_ID=${k.accessKeyId}`, `export AWS_SECRET_ACCESS_KEY=${k.secretAccessKey}`, `export AWS_REGION=${region}`,
|
|
453
|
+
`export AWS_ENDPOINT_URL_LAMBDA=${ep}`, `export AWS_ENDPOINT_URL_SQS=${ep}`, `export AWS_ENDPOINT_URL_SCHEDULER=${ep}`, `export AWS_ENDPOINT_URL_EVENTBRIDGE=${ep}`, `export AWS_ENDPOINT_URL_CLOUDWATCH_LOGS=${ep}`].join("\n") + "\n");
|
|
454
|
+
if (process.stderr.isTTY) warn("A new access key was created (Access keys in the dashboard lists and deletes them).");
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function defaultName(p: string, src: Source): string {
|
|
459
|
+
const base = p === "." ? path.basename(process.cwd()) : fs.existsSync(p) && fs.statSync(p).isDirectory() ? path.basename(path.resolve(p)) : path.basename(p).replace(/\.[^.]+$/, "");
|
|
460
|
+
const n = (["handler", "lambda_function", "index", "main", "app", "bootstrap"].includes(base) ? path.basename(path.resolve(path.dirname(p === "." ? "./x" : p))) : base)
|
|
461
|
+
.replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64);
|
|
462
|
+
return n || `fn-${src.lang}`;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** The region holding the function: --region, or the one region where it exists. */
|
|
466
|
+
async function existingAccount(o: any, name: string): Promise<Account> {
|
|
467
|
+
const { projectId } = await resolveProjectScope(o.project);
|
|
468
|
+
const all = await accounts(projectId);
|
|
469
|
+
if (o.region) {
|
|
470
|
+
const region = await resolveRegion(o.region);
|
|
471
|
+
const a = all.find((x) => x.region === region);
|
|
472
|
+
if (!a) fail(`No functions in ${region} for this project`, 1, "NOT_FOUND");
|
|
473
|
+
return a!;
|
|
474
|
+
}
|
|
475
|
+
const holding: Account[] = [];
|
|
476
|
+
for (const a of all) if (await getFn(a, name).catch(() => null)) holding.push(a);
|
|
477
|
+
if (!holding.length) fail(`Function ${name} not found (lizard fn ls)`, 1, "NOT_FOUND");
|
|
478
|
+
if (holding.length > 1) fail(`${name} exists in ${holding.map((a) => a.region).join(" and ")}: pass --region`, 2);
|
|
479
|
+
return holding[0];
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function parseDuration(s: string): number {
|
|
483
|
+
const m = String(s).match(/^(\d+)\s*(s|m|h|d)?$/);
|
|
484
|
+
if (!m) fail(`--since takes e.g. 30s, 10m, 2h, 1d (got ${s})`, 2);
|
|
485
|
+
return Number(m![1]) * ({ s: 1e3, m: 6e4, h: 36e5, d: 864e5 } as Record<string, number>)[m![2] ?? "m"];
|
|
486
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -87,6 +87,7 @@ import { registerPause } from "./commands/pause.js";
|
|
|
87
87
|
import { registerRestart } from "./commands/restart.js";
|
|
88
88
|
import { registerRun } from "./commands/run.js";
|
|
89
89
|
import { registerS3 } from "./commands/s3.js";
|
|
90
|
+
import { registerFn } from "./commands/fn.js";
|
|
90
91
|
import { registerSandbox } from "./commands/sandbox.js";
|
|
91
92
|
import { registerAgents } from "./commands/agents.js";
|
|
92
93
|
import { registerScale } from "./commands/scale.js";
|
|
@@ -188,6 +189,7 @@ registerPause(program);
|
|
|
188
189
|
registerRestart(program);
|
|
189
190
|
registerRun(program);
|
|
190
191
|
registerS3(program);
|
|
192
|
+
registerFn(program);
|
|
191
193
|
registerSandbox(program);
|
|
192
194
|
registerAgents(program);
|
|
193
195
|
registerScale(program);
|