@lizard-build/cli 4.0.99 → 4.0.100

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.
@@ -9,39 +9,69 @@ Use a function for: an API endpoint or webhook (`--url`), a cron job (`--schedul
9
9
  scraper or a data job you call from code, work queued from elsewhere. Use `lizard up` (a
10
10
  service) instead for a long-running server or anything with its own process manager.
11
11
 
12
- ## One command: `lizard fn deploy`
12
+ ## The whole loop, for agents
13
+
14
+ 1. Write the handler file (Python, Node.js, TypeScript, Ruby, Go or Rust).
15
+ 2. Run `lizard fn deploy <path> --json` (add `--schedule "every hour"` for a job, `--test` to call it once).
16
+ 3. If `status` is not `"ready"`, run the `remediation` command exactly, then go back to 2.
17
+
18
+ Deploy is idempotent by name and checks that the code **starts** before it takes traffic: an
19
+ update that fails to start leaves the previous version serving (`serving.unchanged: true`).
20
+
21
+ ## `lizard fn deploy`
13
22
 
14
23
  ```bash
15
- lizard fn deploy handler.py --packages requests,beautifulsoup4 --url --json
24
+ lizard fn deploy scraper.py --schedule "every hour" --json
16
25
  ```
17
26
 
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`,
27
+ - **Source**: a file, a directory, or `-` (stdin, with `--name` and `--runtime`). Language,
28
+ runtime and handler come from the source (`def handler(event, context)`,
29
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.
30
+ TypeScript (`index.ts`), Go (`main.go` / `go.mod`) and Rust (`Cargo.toml`) are compiled on Lizard.
31
+ - **Packages, one rule** (the result's `packages.source` says which applied):
32
+ 1. a dependency file in the source (`requirements.txt`, `package.json` with dependencies,
33
+ `Gemfile`, `go.mod`, `Cargo.toml`) is built into the code (`"file"`);
34
+ 2. otherwise `--packages a,b==1.2` (`"flag"`; `--packages ''` removes them);
35
+ 3. otherwise the packages the imports need are installed (`"imports"`: `bs4` ->
36
+ `beautifulsoup4`, `PIL` -> `pillow`, `yaml` -> `pyyaml`...); `--no-infer` turns it off.
37
+ Exact versions come back in `packages.resolved`; an unchanged list is not reinstalled
38
+ (`"cache": "hit"`). A dependency file and `--packages` together fail with `PACKAGES_CONFLICT`;
39
+ `import google` fails with `AMBIGUOUS_IMPORT` (name the package).
40
+ - **URL**: on by default for handlers that read HTTP events (`statusCode`, `rawPath`,
41
+ `queryStringParameters`...); `--url` / `--no-url`; `--auth key` requires signed requests.
42
+ The event is a function-URL event; return `{"statusCode": 200, "headers": {...}, "body": "..."}`.
43
+ - **Schedule**: `--schedule` takes `"every 15 minutes"`, `"hourly"`, `"daily at 09:00"`,
44
+ `"weekdays at 9am"`, `"every monday at 18:30"`, a 5-field cron (`"*/5 * * * *"`),
45
+ `rate(...)` or `cron(...)`; times are UTC; the result shows the expression and the next
46
+ runs. `--schedule off` removes it.
47
+ - **Settings**: `--env KEY=VALUE` (repeatable), `--memory <MB>`, `--timeout <s>`,
48
+ `--region us|eu`, `--project <id>`. `--test [event]` calls it after deploying (GET / for URL
49
+ functions) and fails with `TEST_FAILED` if it errors. `--no-check` skips the start check.
50
+ - Every deploy that changes something is a numbered **version** (`version` in the result).
51
+
52
+ Success (`--json`, stdout):
53
+ ```json
54
+ {"schemaVersion": 1, "status": "ready", "name": "scraper", "region": "us-east-1", "version": 1, "created": true,
55
+ "changed": ["code", "packages", "schedule"], "runtime": "python3.13", "handler": "scraper.handler",
56
+ "packages": {"source": "imports", "resolved": {"requests": "2.34.2", "beautifulsoup4": "4.15.0"}, "cache": "miss"},
57
+ "check": {"kind": "start", "ok": true}, "url": null,
58
+ "schedule": {"input": "every hour", "expression": "rate(1 hour)", "timezone": "UTC", "nextRuns": ["..."]},
59
+ "next": [{"label": "run the schedule now", "command": "lizard fn invoke scraper --as-schedule --json"}]}
60
+ ```
61
+
62
+ Failure (stdout empty, one JSON object on stderr, exit code below):
63
+ ```json
64
+ {"schemaVersion": 1, "status": "failed", "phase": "check", "code": "IMPORT_ERROR",
65
+ "error": "The function failed to start: No module named 'yaml'", "missing": ["pyyaml"],
66
+ "serving": {"version": 1, "unchanged": true}, "logTail": "...",
67
+ "remediation": "lizard fn deploy scraper.py --packages requests,pyyaml --json"}
68
+ ```
69
+
70
+ Codes: `INVALID_INPUT`, `INVALID_SCHEDULE`, `NOT_FOUND`, `REGION_REQUIRED`, `SOURCE_TOO_LARGE`,
71
+ `IMPORT_ERROR` (with `missing`), `HANDLER_NOT_FOUND` (with `candidates`), `START_FAILED`,
72
+ `BUILD_FAILED` (with `logTail`), `PACKAGES_CONFLICT`, `AMBIGUOUS_IMPORT`, `TEST_FAILED`,
73
+ `BUSY`, `TIMEOUT`. Exit codes: 0 ready, 1 build / start / test failure, 2 not signed in,
74
+ 3 invalid input or not found, 4 timeout.
45
75
 
46
76
  ## Calling and watching
47
77
 
@@ -49,6 +79,7 @@ unchanged file and unchanged packages are a no-op (about 2 s), a code change abo
49
79
  lizard fn invoke <name> '{"url": "https://example.com"}' --json # result (+ --logs)
50
80
  lizard fn invoke <name> - < event.json
51
81
  lizard fn invoke <name> '{}' --async # queued, returns at once
82
+ lizard fn invoke <name> --as-schedule --json # the event its schedule sends (run a job now)
52
83
  lizard fn logs <name> --since 10m [-f] # print() / console.log output
53
84
  lizard fn ls --json # every region
54
85
  lizard fn rm <name>
@@ -106,7 +137,7 @@ func main() { lambda.Start(handler) }
106
137
 
107
138
  - The first function of a runtime in a region takes up to a minute (the runtime image is
108
139
  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).
140
+ - Calls keep working during deploys and package installs: the new code starts next to the
141
+ running one and takes over once it has started.
111
142
  - Billing is the sandbox time the function's environments use (paused is free).
112
143
  - The dashboard's Functions page shows the same functions (code editor, test, logs, packages).
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import * as os from "node:os";
4
4
  import * as zlib from "node:zlib";
5
+ import * as crypto from "node:crypto";
5
6
  import { createHash } from "node:crypto";
6
7
  import chalk from "chalk";
7
8
  import { Command } from "commander";
@@ -52,8 +53,8 @@ export function detectSource(p: string, opts: { runtime?: string; handler?: stri
52
53
  const names = files.map((f) => f.name);
53
54
  const lang: Lang = langOfRuntime(opts.runtime) ?? (names.includes("Cargo.toml") ? "rust" : names.includes("go.mod") || entry.endsWith(".go") ? "go"
54
55
  : /\.py$/.test(entry) ? "python" : /\.(m?js|cjs)$/.test(entry) ? "node" : /\.rb$/.test(entry) ? "ruby" : entry === "bootstrap" ? "shell"
55
- : /\.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")
56
- : (fail(`Can't tell the language of ${entry}: pass --runtime (e.g. python3.13, nodejs22.x, ruby3.3, provided.al2023)`, 2), "python"));
56
+ : /\.(ts|mts|cts)$/.test(entry) ? "node" // compiled on Lizard (esbuild)
57
+ : (() => { throw Object.assign(new Error(`Can't tell the language of ${entry}: pass --runtime (e.g. python3.13, nodejs22.x, ruby3.3, provided.al2023)`), { code: "INVALID_INPUT", remediation: `lizard fn deploy ${entry} --runtime python3.13 --json` }); })());
57
58
  const text = files.find((f) => f.name === entry)?.data.toString("utf8") ?? "";
58
59
  const handler = opts.handler ?? (lang === "go" || lang === "rust" || lang === "shell" ? "bootstrap" : findHandler(lang, entry, text));
59
60
  const deps = names.some((n) => ["requirements.txt", "Gemfile", "go.mod", "Cargo.toml"].includes(n))
@@ -83,7 +84,7 @@ function walk(root: string, rel = ""): Source["files"] {
83
84
  out.push({ name: r, data: fs.readFileSync(path.join(root, r)), mode: st.mode & 0o111 ? 0o100755 : undefined });
84
85
  }
85
86
  const size = out.reduce((n, f) => n + f.data.length, 0);
86
- 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);
87
+ if (size > 50 * 1024 * 1024) throw Object.assign(new Error(`${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)`), { code: "SOURCE_TOO_LARGE", remediation: "lizard fn deploy <smaller directory> --json" });
87
88
  return out;
88
89
  }
89
90
 
@@ -91,15 +92,16 @@ function pickEntry(names: string[]): string {
91
92
  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"]) {
92
93
  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;
93
94
  }
95
+ for (const n of ["index.ts", "handler.ts", "app.ts"]) if (names.includes(n)) return n;
94
96
  const top = names.filter((n) => !n.includes("/"));
95
- const guess = top.find((n) => /\.(py|m?js|cjs|rb|go)$/.test(n));
96
- if (!guess) fail("No function file found: name it handler.py, index.mjs, lambda_function.rb, main.go (or pass a file)", 2);
97
+ const guess = top.find((n) => /\.(py|m?js|cjs|rb|go|ts)$/.test(n) && !n.endsWith(".d.ts"));
98
+ if (!guess) throw Object.assign(new Error("No function file found: name it handler.py, index.mjs, index.ts, lambda_function.rb, main.go (or pass a file)"), { code: "INVALID_INPUT", remediation: "lizard fn deploy handler.py --json" });
97
99
  return guess!;
98
100
  }
99
101
 
100
102
  /** The handler (module.function) from the source, as Lambda names it. */
101
103
  export function findHandler(lang: Lang, entry: string, text: string): string {
102
- const mod = entry.replace(/\.(py|m?js|cjs|rb)$/, "");
104
+ const mod = entry.replace(/\.(py|m?js|cjs|rb|ts|mts|cts)$/, "");
103
105
  if (lang === "python") {
104
106
  const names = [...text.matchAll(/^(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)/gm)].map((m) => m[1]);
105
107
  const fn = ["lambda_handler", "handler", "main"].find((n) => names.includes(n)) ?? names[0] ?? "lambda_handler";
@@ -157,7 +159,7 @@ async function resolveRegion(flag?: string): Promise<string> {
157
159
  const all = await regions();
158
160
  if (!flag) return all.includes("us-east-1") ? "us-east-1" : all[0] ?? "us-east-1";
159
161
  const r = REGION_ALIASES[flag] ?? flag;
160
- if (all.length && !all.includes(r)) fail(`Lizard Functions runs in ${all.join(", ")} (aliases: us, eu); not in ${flag}`, 2);
162
+ if (all.length && !all.includes(r)) fail(`Lizard Functions runs in ${all.join(", ")} (aliases: us, eu); not in ${flag}`, 3, "INVALID_INPUT");
161
163
  return r;
162
164
  }
163
165
  async function accounts(projectId: string): Promise<Account[]> {
@@ -221,7 +223,7 @@ async function waitBuild(acct: Account, id: string, spinner: (s: string) => void
221
223
  function parseEnv(list: string[] | undefined): Record<string, string> | undefined {
222
224
  if (!list?.length) return undefined;
223
225
  const out: Record<string, string> = {};
224
- 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); }
226
+ for (const kv of list) { const i = kv.indexOf("="); if (i < 1) fail(`--env takes KEY=VALUE (got ${kv})`, 3, "INVALID_INPUT"); out[kv.slice(0, i)] = kv.slice(i + 1); }
225
227
  return out;
226
228
  }
227
229
  const splitList = (v?: string[] | string) => (Array.isArray(v) ? v : v ? [v] : []).flatMap((x) => x.split(/[,\s]+/)).map((x) => x.trim()).filter(Boolean);
@@ -248,120 +250,119 @@ Examples:
248
250
  eval "$(lizard fn env)" # AWS SDK / CLI credentials and endpoint`);
249
251
 
250
252
  fn.command("deploy")
251
- .description("Create or update a function from a file, a directory or stdin (-); installs packages, waits until it is ready")
253
+ .description("Create or update a function from a file, a directory or stdin (-): packages, build, start check, URL, schedule; waits until it is ready")
252
254
  .argument("[path]", "file, directory or - for stdin", ".")
253
255
  .option("--name <name>", "function name (default: from the file or directory)")
254
256
  .option("--runtime <runtime>", "e.g. python3.13, nodejs22.x, ruby3.3, provided.al2023 (default: from the source)")
255
257
  .option("--handler <handler>", "e.g. app.handler (default: found in the source)")
256
- .option("--packages <list...>", "libraries to preinstall, e.g. requests numpy==2.1.3 (comma or space separated)")
258
+ .option("--packages <list...>", "libraries, e.g. requests numpy==2.1.3 (comma or space separated; '' removes them). Default: a requirements.txt / package.json in the source, else what the imports need")
259
+ .option("--no-infer", "don't install packages from the imports when none are declared")
257
260
  .option("--env <KEY=VALUE...>", "environment variables")
258
261
  .option("--memory <mb>", "memory in MB", (v) => parseInt(v, 10))
259
262
  .option("--timeout <seconds>", "timeout in seconds", (v) => parseInt(v, 10))
260
- .option("--url", "give it a public HTTPS URL")
261
- .option("--schedule <expression>", 'run it on a schedule: "rate(5 minutes)" or "cron(0 9 * * ? *)"')
263
+ .option("--url", "give it a public HTTPS URL (default: on for handlers that read HTTP events)")
264
+ .option("--no-url", "no URL")
265
+ .option("--auth <mode>", "URL access: none (public, default) or key (requests must be signed with an access key)")
266
+ .option("--schedule <when>", 'run it on a schedule: "every hour", "daily at 09:00", "*/5 * * * *", rate(...) or cron(...); "off" removes it')
267
+ .option("--test [event]", "after deploying, call it with this event (default {} / GET / for URL functions) and fail if it errors")
268
+ .option("--no-check", "skip the start check (the new code takes traffic without being started first)")
262
269
  .option("--region <region>", "us-east-1 (us) or eu-west-lim-a (eu)")
263
270
  .option("--project <id>", "project (default: the linked one)")
264
271
  .action(async (p: string, o: any) => {
265
272
  const t0 = Date.now(); tStart = t0;
266
273
  const stdin = p === "-" ? fs.readFileSync(0, "utf8") : undefined;
267
- if (p !== "-" && !fs.existsSync(p)) fail(`${p} does not exist`, 2);
268
- if (stdin !== undefined && !o.name) fail("--name is required with stdin", 2);
269
- const src = detectSource(p, { runtime: o.runtime, handler: o.handler, stdin });
270
- const name: string = o.name ?? defaultName(p, src);
271
- if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) fail(`Function name ${name}: letters, numbers, hyphens and underscores, up to 64 (pass --name)`, 2);
272
- const runtime = o.runtime && !/^(go|rust)$/.test(o.runtime) ? o.runtime : DEFAULT_RUNTIME[src.lang];
273
- const packages = splitList(o.packages);
274
+ if (p !== "-" && !fs.existsSync(p)) failEnv({ code: "INVALID_INPUT", error: `${p} does not exist`, remediation: "lizard fn deploy <file or directory> --json" }, 3);
275
+ if (stdin !== undefined && !o.name) failEnv({ code: "INVALID_INPUT", error: "--name is required with stdin", remediation: "echo '...' | lizard fn deploy - --name <name> --runtime python3.13 --json" }, 3);
276
+ let src: Source;
277
+ try { src = detectSource(p, { runtime: o.runtime, handler: o.handler, stdin }); }
278
+ catch (e: any) { failEnv({ code: e.code || "INVALID_INPUT", error: e.message, remediation: e.remediation || "lizard fn deploy <path> --runtime python3.13 --json" }, 3); }
279
+ const name: string = o.name ?? defaultName(p, src!);
280
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) failEnv({ code: "INVALID_INPUT", error: `Function name ${name}: letters, numbers, hyphens and underscores, up to 64`, remediation: `lizard fn deploy ${p} --name my-function --json` }, 3);
281
+ const runtime = o.runtime && !/^(go|rust)$/.test(o.runtime) ? o.runtime : DEFAULT_RUNTIME[src!.lang];
274
282
  const { projectId } = await resolveProjectScope(o.project);
275
283
  const region = await resolveRegion(o.region);
276
284
  status(`account in ${region}…`);
277
285
  const acct = (await accountFor(projectId, region, true))!;
278
- const zipBuf = zipFiles(src.files);
279
- const zip = zipBuf.toString("base64");
280
- const zipSha = createHash("sha256").update(zipBuf).digest("base64");
281
- const config: Record<string, unknown> = { Runtime: runtime, Handler: src.handler };
282
- if (o.memory) config.MemorySize = o.memory;
283
- if (o.timeout) config.Timeout = o.timeout;
286
+ const body: Record<string, unknown> = { ZipFile: zipFiles(src!.files).toString("base64"), Runtime: runtime, Handler: src!.handler };
287
+ if (o.packages !== undefined) body.Packages = splitList(o.packages);
288
+ if (o.infer === false) body.Infer = false;
289
+ if (o.check === false) body.Check = false;
290
+ if (o.memory) body.MemorySize = o.memory;
291
+ if (o.timeout) body.Timeout = o.timeout;
284
292
  const env = parseEnv(o.env);
285
- if (env) config.Environment = { Variables: env };
286
- const existing = await getFn(acct, name);
287
- const compiled = src.lang === "go" || src.lang === "rust";
288
- let created = false;
289
-
290
- // Code: built on Lizard when it has a dependency file (or is Go / Rust), else sent as is.
291
- if (src.deps || compiled) {
292
- status(existing ? "building…" : "creating (building)…");
293
- if (existing) await waitReady(acct, name);
294
- if (existing) await aws(acct, "PUT", `${fnPath(name)}/configuration`, config);
295
- if (existing) await waitReady(acct, name);
296
- const job = (await aws(acct, "POST", `lizard/functions/${encodeURIComponent(name)}/build`, {
297
- ZipFile: zip, Runtime: runtime, ...(compiled && packages.length ? { Packages: packages } : {}),
298
- ...(existing ? {} : { Create: { Role: "arn:aws:iam::000000000000:role/lizard-function", MemorySize: 512, Timeout: 30, ...config } }),
299
- })).data;
300
- const b = await waitBuild(acct, job.BuildId, status);
301
- if (b.Status !== "Succeeded") { statusDone(); fail(`Build failed: ${b.Error}\n${String(b.Log || "").slice(-3000)}`, 1, "BUILD_FAILED"); }
302
- created = !existing;
303
- } else if (existing) {
304
- // Only what changed is sent: the same code (by SHA-256) and the same settings are no-ops.
305
- const c = existing.Configuration ?? {};
306
- if (c.LastUpdateStatus === "InProgress") await waitReady(acct, name);
307
- if (c.CodeSha256 !== zipSha) {
308
- status("updating code…");
309
- await aws(acct, "PUT", `${fnPath(name)}/code`, { ZipFile: zip });
310
- }
311
- const changed = Object.entries(config).some(([k, v]) => JSON.stringify(k === "Environment" ? { Variables: c.Environment?.Variables ?? {} } : c[k]) !== JSON.stringify(v));
312
- if (changed) {
313
- status("updating settings…");
314
- await waitReady(acct, name);
315
- await aws(acct, "PUT", `${fnPath(name)}/configuration`, config);
316
- }
317
- } else {
318
- status("creating…");
319
- 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 } });
320
- created = true;
293
+ if (env) body.Environment = { Variables: env };
294
+ // --url / --no-url / default: "auto" (the service decides from the handler).
295
+ if (process.argv.includes("--no-url")) body.Url = false; else if (process.argv.includes("--url")) body.Url = true;
296
+ if (o.auth) {
297
+ if (!["none", "key", "public", "iam"].includes(o.auth)) failEnv({ code: "INVALID_INPUT", error: "--auth is none or key", remediation: `lizard fn deploy ${p} --auth key --json` }, 3);
298
+ body.UrlAuth = ["key", "iam"].includes(o.auth) ? "AWS_IAM" : "NONE";
299
+ if (!body.Url) body.Url = true;
321
300
  }
301
+ if (o.schedule !== undefined) body.Schedule = /^(off|none|no)$/i.test(o.schedule) ? "" : o.schedule;
322
302
 
323
- // Packages (Node.js / Python / Ruby): the function's own layer, rebuilt only when the list changes.
324
- let installed: string[] | null = null;
325
- if (!compiled) {
326
- 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…"));
327
- const cur = (await aws(acct, "GET", `lizard/functions/${encodeURIComponent(name)}/packages`)).data;
328
- const same = JSON.stringify([...(cur.Packages ?? [])].sort()) === JSON.stringify([...packages].sort());
329
- if (o.packages !== undefined && !same) {
330
- status("installing packages…");
331
- const job = (await aws(acct, "PUT", `lizard/functions/${encodeURIComponent(name)}/packages`, { Packages: packages })).data;
332
- if (job.BuildId) {
333
- const b = await waitBuild(acct, job.BuildId, status);
334
- if (b.Status !== "Succeeded") { statusDone(); fail(`Installing packages failed: ${b.Error}\n${String(b.Log || "").slice(-3000)}`, 1, "BUILD_FAILED"); }
335
- }
336
- }
337
- installed = o.packages !== undefined ? packages : cur.Packages ?? [];
303
+ status("deploying…");
304
+ let start;
305
+ try { start = (await aws(acct, "POST", `lizard/functions/${encodeURIComponent(name)}/deploy`, body)).data; }
306
+ catch (e) {
307
+ if (e instanceof APIError && e.status === 400) failEnv({ code: /schedule/i.test(e.message) ? "INVALID_SCHEDULE" : "INVALID_INPUT", error: e.message, remediation: /schedule/i.test(e.message) ? `lizard fn deploy ${p} --schedule "every hour" --json` : `lizard fn deploy ${p} --json` }, 3);
308
+ if (e instanceof APIError && e.status === 409) failEnv({ code: "BUSY", error: e.message, remediation: `lizard fn deploy ${p} --json` }, 1);
309
+ throw e;
310
+ }
311
+ let d: any;
312
+ const end = Date.now() + 20 * 60_000;
313
+ for (;;) {
314
+ d = (await aws(acct, "GET", `lizard/deploys/${start.deployId}`)).data;
315
+ if (d.status !== "deploying") break;
316
+ status({ prepare: "preparing…", build: "building…", packages: "installing packages…", check: "starting the new code…" }[d.phase as string] ?? "deploying…");
317
+ if (Date.now() > end) failEnv({ code: "TIMEOUT", error: "The deploy did not finish in 20 minutes", remediation: `lizard fn deploy ${p} --json` }, 4);
318
+ await sleep(500);
319
+ }
320
+ statusDone();
321
+ const where = o.region ? ` --region ${region}` : "";
322
+ if (d.status !== "ready") {
323
+ failEnv({ ...d, phase: d.phase, remediation: remediationFor(d, p, src!, o), next: undefined }, 1);
338
324
  }
339
- 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…"));
340
325
 
341
- // URL and schedule.
342
- let url: string | null = null;
343
- if (o.url) {
344
- try { url = (await aws(acct, "GET", `2021-10-31/functions/${encodeURIComponent(name)}/url`)).data.FunctionUrl; }
345
- catch (e) {
346
- if (!(e instanceof APIError && e.status === 404)) throw e;
347
- url = (await aws(acct, "POST", `2021-10-31/functions/${encodeURIComponent(name)}/url`, { AuthType: "NONE", Cors: { AllowOrigins: ["*"] } })).data.FunctionUrl;
326
+ // --test: call it now (a URL function gets a GET / unless an event is given).
327
+ let test: any = null;
328
+ if (o.test !== undefined) {
329
+ status("testing…");
330
+ if (d.url?.value && o.test === true) {
331
+ const r = await fetch(d.url.value, { signal: AbortSignal.timeout(60_000) }).catch((e) => ({ ok: false, status: 0, text: async () => String(e) } as any));
332
+ const text = await r.text();
333
+ test = { kind: "http", request: "GET /", status: r.status, ok: r.status > 0 && r.status < 500, body: text.slice(0, 2000) };
334
+ } else {
335
+ let ev: unknown = {};
336
+ if (typeof o.test === "string") { try { ev = JSON.parse(o.test); } catch { failEnv({ code: "INVALID_INPUT", error: "--test takes event JSON", remediation: `lizard fn deploy ${p} --test '{}' --json` }, 3); } }
337
+ const r = await aws(acct, "POST", `${fnPath(name)}/invocations`, ev, { headers: { "x-amz-log-type": "Tail" } });
338
+ const err = r.headers.get("x-amz-function-error");
339
+ const tail = r.headers.get("x-amz-log-result");
340
+ test = { kind: "invoke", ok: !err, error: err || undefined, result: r.data ?? null, logTail: tail ? Buffer.from(tail, "base64").toString("utf8").slice(-3000) : undefined };
348
341
  }
342
+ statusDone();
343
+ if (!test.ok) failEnv({ schemaVersion: 1, status: "failed", phase: "test", code: "TEST_FAILED", name, region, version: d.version,
344
+ error: test.kind === "http" ? `GET / answered ${test.status}` : `The test invocation raised ${test.error}`, test, remediation: `lizard fn logs ${name}${where} --since 5m --json`,
345
+ serving: { version: d.version, unchanged: false } }, 1);
349
346
  }
350
- if (o.schedule) {
351
- const body = { ScheduleExpression: o.schedule, FlexibleTimeWindow: { Mode: "OFF" }, Target: { Arn: cfg.FunctionArn, RoleArn: "arn:aws:iam::000000000000:role/lizard-scheduler" }, State: "ENABLED" };
352
- try { await aws(acct, "PUT", `schedules/${encodeURIComponent(name)}`, body); }
353
- catch (e) { if (e instanceof APIError && e.status === 404) await aws(acct, "POST", `schedules/${encodeURIComponent(name)}`, body); else throw e; }
354
- }
355
- statusDone();
356
- const secs = ((Date.now() - t0) / 1000).toFixed(1);
357
- const out = { name, region, created, runtime: cfg.Runtime, handler: cfg.Handler, language: src.lang, arn: cfg.FunctionArn, packages: installed, url, schedule: o.schedule ?? null,
358
- seconds: Number(secs), invoke: `lizard fn invoke ${name}${o.region ? ` --region ${region}` : ""} '{}'` };
347
+
348
+ const next = [
349
+ d.schedule ? { label: "run the schedule now", command: `lizard fn invoke ${name}${where} --as-schedule --json` } : { label: "call it", command: `lizard fn invoke ${name}${where} '{}' --json` },
350
+ ...(d.url?.value ? [{ label: "call the URL", command: `curl -s ${d.url.value}` }] : []),
351
+ { label: "logs", command: `lizard fn logs ${name}${where} --since 5m --json` },
352
+ ];
353
+ const out = { schemaVersion: 1, status: "ready", name, region, version: d.version, created: d.created, changed: d.changed, runtime: d.runtime, handler: d.handler, language: d.language,
354
+ packages: d.packages, check: d.check, test, url: d.url ?? null, schedule: d.schedule ?? null, seconds: Number(((Date.now() - t0) / 1000).toFixed(1)), next };
359
355
  if (isJSONMode()) return printJSON(out);
360
- success(`${created ? "Created" : "Updated"} ${chalk.bold(name)} in ${region} (${cfg.Runtime}, ${cfg.Handler}) in ${secs}s`);
361
- if (installed?.length) info(`Packages: ${installed.join(" ")}`);
362
- if (url) info(`URL: ${chalk.cyan(url)}`);
363
- if (o.schedule) info(`Schedule: ${o.schedule}`);
364
- info(`Call it: ${chalk.cyan(out.invoke)}`);
356
+ const pk = d.packages ?? {};
357
+ const resolved = pk.resolved ? Object.entries(pk.resolved).map(([k, v]) => `${k} ${v}`).join(", ") : (pk.requested ?? []).join(", ");
358
+ const srcLabel = { file: "from the dependency file", flag: "from --packages", imports: "from the imports", none: "" }[pk.source as string] ?? "";
359
+ if (pk.source !== "none" && resolved) console.log(`${chalk.dim("Packages ")} ${resolved} ${chalk.dim(`(${srcLabel}${pk.cache === "hit" ? ", cached" : pk.installSeconds ? `, installed in ${pk.installSeconds}s` : ""})`)}`);
360
+ console.log(`${chalk.green(d.created ? "Created " : d.changed?.length ? "Updated " : "Unchanged")} ${chalk.bold(name)} in ${region} · ${d.runtime} · ${d.handler} · version ${d.version} · ${out.seconds}s`);
361
+ if (d.check?.kind === "start") console.log(`${chalk.dim("Checked ")} module loads and handler found${d.check.coldStartMs ? ` (cold start ${d.check.coldStartMs} ms)` : ""}`);
362
+ if (test) console.log(`${chalk.dim("Tested ")} ${test.kind === "http" ? `GET / -> ${test.status}` : "invoked, no error"}`);
363
+ if (d.url?.value) console.log(`${chalk.dim("URL ")} ${chalk.cyan(d.url.value)} ${d.url.auth === "none" ? "public (--auth key to require a key)" : "requires a signed request"}`);
364
+ if (d.schedule) console.log(`${chalk.dim("Schedule ")} ${d.schedule.input !== d.schedule.expression ? `${d.schedule.input} = ` : ""}${d.schedule.expression} ${d.schedule.timezone} · next ${d.schedule.nextRuns?.[0] ?? "-"}`);
365
+ console.log(`${chalk.dim("Next ")} ${next.map((n) => n.command).join("\n ")}`);
365
366
  });
366
367
 
367
368
  fn.command("invoke")
@@ -370,17 +371,25 @@ Examples:
370
371
  .argument("[event]", "event JSON (default {}; - reads stdin)", "{}")
371
372
  .option("--logs", "print the invocation's log")
372
373
  .option("--async", "queue it (InvocationType Event) and return at once")
374
+ .option("--as-schedule", "send the event its schedule sends (run a scheduled job now)")
373
375
  .option("--region <region>").option("--project <id>")
374
376
  .action(async (name: string, event: string, o: any) => {
375
377
  const acct = await existingAccount(o, name);
376
378
  const body = event === "-" ? fs.readFileSync(0, "utf8") : event;
377
379
  let parsed: unknown;
378
- try { parsed = JSON.parse(body); } catch { fail("The event must be JSON", 2); }
380
+ try { parsed = JSON.parse(body); } catch { fail("The event must be JSON", 3, "INVALID_INPUT"); }
381
+ if (o.asSchedule) {
382
+ // EventBridge Scheduler's event for a function, as `lizard fn deploy --schedule` sets it.
383
+ const s = await aws(acct, "GET", `schedules/${encodeURIComponent(name)}`).catch(() => null);
384
+ let input: any = { source: "lizard.schedule", "detail-type": "Scheduled Event", detail: {} };
385
+ try { if (s?.data?.Target?.Input) input = JSON.parse(s.data.Target.Input); } catch { /* default */ }
386
+ parsed = { ...input, time: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), id: crypto.randomUUID() };
387
+ }
379
388
  const r = await aws(acct, "POST", `${fnPath(name)}/invocations`, parsed, { headers: { "x-amz-log-type": "Tail", ...(o.async ? { "x-amz-invocation-type": "Event" } : {}) } });
380
389
  const err = r.headers.get("x-amz-function-error");
381
390
  const tail = r.headers.get("x-amz-log-result");
382
391
  const logs = tail ? Buffer.from(tail, "base64").toString("utf8") : "";
383
- 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 }); }
392
+ if (isJSONMode()) { if (err) process.exitCode = EXIT.FAILED; return printJSON({ status: o.async ? "queued" : err ? "error" : "ok", error: err || undefined, result: r.data ?? null, logs: o.logs ? logs : undefined }); }
384
393
  if (o.logs && logs) process.stderr.write(chalk.dim(logs.endsWith("\n") ? logs : logs + "\n"));
385
394
  if (o.async) return success("Queued");
386
395
  process.stdout.write((typeof r.data === "string" ? r.data : JSON.stringify(r.data ?? null, null, 2)) + "\n");
@@ -479,6 +488,40 @@ Examples:
479
488
  });
480
489
  }
481
490
 
491
+ // One table of exit codes for the whole CLI: 0 ok, 1 build/check/test failure, 2 authentication,
492
+ // 3 invalid input or not found, 4 timeout.
493
+ export const EXIT = { OK: 0, FAILED: 1, AUTH: 2, INVALID: 3, TIMEOUT: 4 } as const;
494
+
495
+ /** A failure for people and agents: stdout empty, one JSON envelope on stderr (--json / no TTY), or readable text. */
496
+ function failEnv(e: Record<string, any>, exit: number): never {
497
+ statusDone();
498
+ const env: Record<string, any> = { schemaVersion: 1, status: "failed", ...e };
499
+ for (const k of Object.keys(env)) if (env[k] === undefined || k === "deployId" || k === "log" || k === "startedAt" || k === "endedAt") delete (env as any)[k];
500
+ if (isJSONMode()) process.stderr.write(JSON.stringify(env, null, 2) + "\n");
501
+ else {
502
+ process.stderr.write(chalk.red(`Error (${env.code}): ${env.error}\n`));
503
+ if (env.serving?.unchanged) process.stderr.write(chalk.dim(`Version ${env.serving.version} is still serving: nothing changed.\n`));
504
+ if (env.logTail) process.stderr.write(chalk.dim(String(env.logTail).trim().split("\n").slice(-12).join("\n") + "\n"));
505
+ if (env.remediation) process.stderr.write(`Fix: ${chalk.cyan(env.remediation)}\n`);
506
+ }
507
+ process.exit(exit);
508
+ }
509
+
510
+ /** The exact command that fixes a failed deploy (every one is a command the CLI's tests run). */
511
+ function remediationFor(d: any, p: string, src: Source, o: any): string {
512
+ const base = `lizard fn deploy ${p}${o.name ? ` --name ${o.name}` : ""}${o.region ? ` --region ${o.region}` : ""}`;
513
+ const have: string[] = d.packages?.requested ?? splitList(o.packages);
514
+ switch (d.code) {
515
+ case "IMPORT_ERROR": return d.missing?.length ? `${base} --packages ${[...new Set([...have, ...d.missing])].join(",")} --json` : `${base} --json # fix the error in the log, then deploy again`;
516
+ case "HANDLER_NOT_FOUND": return d.candidates?.length ? `${base} --handler ${d.candidates[0]} --json` : `${base} --handler <module>.<function> --json`;
517
+ case "PACKAGES_CONFLICT": return `${base} --json # list packages in ${d.packages?.file ?? "the dependency file"} only (drop --packages)`;
518
+ case "AMBIGUOUS_IMPORT": return `${base} --packages <the package you need, e.g. ${String(d.ambiguous?.[0]?.choices ?? "").split(",")[0].trim()}> --json`;
519
+ case "BUILD_FAILED": return d.packages?.notFound ? `${base} --packages ${have.filter((x) => x !== d.packages.notFound).join(",") || "''"} --json # ${d.packages.notFound} does not exist` : `${base} --json # fix the build error in logTail`;
520
+ case "INVALID_SCHEDULE": return `${base} --schedule "every hour" --json`;
521
+ default: return `${base} --json`;
522
+ }
523
+ }
524
+
482
525
  function defaultName(p: string, src: Source): string {
483
526
  const base = p === "." ? path.basename(process.cwd()) : fs.existsSync(p) && fs.statSync(p).isDirectory() ? path.basename(path.resolve(p)) : path.basename(p).replace(/\.[^.]+$/, "");
484
527
  const n = (["handler", "lambda_function", "index", "main", "app", "bootstrap"].includes(base) ? path.basename(path.resolve(path.dirname(p === "." ? "./x" : p))) : base)
@@ -493,18 +536,18 @@ async function existingAccount(o: any, name: string): Promise<Account> {
493
536
  if (o.region) {
494
537
  const region = await resolveRegion(o.region);
495
538
  const a = all.find((x) => x.region === region);
496
- if (!a) fail(`No functions in ${region} for this project`, 1, "NOT_FOUND");
539
+ if (!a) fail(`No functions in ${region} for this project`, 3, "NOT_FOUND");
497
540
  return a!;
498
541
  }
499
542
  const holding: Account[] = [];
500
543
  for (const a of all) if (await getFn(a, name).catch(() => null)) holding.push(a);
501
- if (!holding.length) fail(`Function ${name} not found (lizard fn ls)`, 1, "NOT_FOUND");
502
- if (holding.length > 1) fail(`${name} exists in ${holding.map((a) => a.region).join(" and ")}: pass --region`, 2);
544
+ if (!holding.length) fail(`Function ${name} not found (lizard fn ls)`, 3, "NOT_FOUND");
545
+ if (holding.length > 1) fail(`${name} exists in ${holding.map((a) => a.region).join(" and ")}: pass --region`, 3, "REGION_REQUIRED");
503
546
  return holding[0];
504
547
  }
505
548
 
506
549
  function parseDuration(s: string): number {
507
550
  const m = String(s).match(/^(\d+)\s*(s|m|h|d)?$/);
508
- if (!m) fail(`--since takes e.g. 30s, 10m, 2h, 1d (got ${s})`, 2);
551
+ if (!m) fail(`--since takes e.g. 30s, 10m, 2h, 1d (got ${s})`, 3, "INVALID_INPUT");
509
552
  return Number(m![1]) * ({ s: 1e3, m: 6e4, h: 36e5, d: 864e5 } as Record<string, number>)[m![2] ?? "m"];
510
553
  }
@@ -5,7 +5,7 @@ import { join, dirname } from "node:path";
5
5
  import os from "node:os";
6
6
  import { spawn } from "node:child_process";
7
7
 
8
- export const CURRENT_VERSION = "4.0.99";
8
+ export const CURRENT_VERSION = "4.0.100";
9
9
  const RELEASES_API = "https://api.github.com/repos/lizard-build/lizard-cli/releases/latest";
10
10
  const RELEASE_BASE = "https://github.com/lizard-build/lizard-cli/releases/latest/download";
11
11