@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.
@@ -31,3 +31,10 @@ export declare function detectSource(p: string, opts?: {
31
31
  export declare function findHandler(lang: Lang, entry: string, text: string): string;
32
32
  export declare function zipFiles(files: Source["files"]): Buffer;
33
33
  export declare function registerFn(program: Command): void;
34
+ export declare const EXIT: {
35
+ readonly OK: 0;
36
+ readonly FAILED: 1;
37
+ readonly AUTH: 2;
38
+ readonly INVALID: 3;
39
+ readonly TIMEOUT: 4;
40
+ };
@@ -2,7 +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 { createHash } from "node:crypto";
5
+ import * as crypto from "node:crypto";
6
6
  import chalk from "chalk";
7
7
  import { api, getBaseURL, getRequestToken, clientHeaders, APIError } from "../lib/api.js";
8
8
  import { resolveProjectScope } from "../lib/resolve.js";
@@ -39,8 +39,8 @@ export function detectSource(p, opts = {}) {
39
39
  const names = files.map((f) => f.name);
40
40
  const lang = langOfRuntime(opts.runtime) ?? (names.includes("Cargo.toml") ? "rust" : names.includes("go.mod") || entry.endsWith(".go") ? "go"
41
41
  : /\.py$/.test(entry) ? "python" : /\.(m?js|cjs)$/.test(entry) ? "node" : /\.rb$/.test(entry) ? "ruby" : entry === "bootstrap" ? "shell"
42
- : /\.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")
43
- : (fail(`Can't tell the language of ${entry}: pass --runtime (e.g. python3.13, nodejs22.x, ruby3.3, provided.al2023)`, 2), "python"));
42
+ : /\.(ts|mts|cts)$/.test(entry) ? "node" // compiled on Lizard (esbuild)
43
+ : (() => { 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` }); })());
44
44
  const text = files.find((f) => f.name === entry)?.data.toString("utf8") ?? "";
45
45
  const handler = opts.handler ?? (lang === "go" || lang === "rust" || lang === "shell" ? "bootstrap" : findHandler(lang, entry, text));
46
46
  const deps = names.some((n) => ["requirements.txt", "Gemfile", "go.mod", "Cargo.toml"].includes(n))
@@ -81,7 +81,7 @@ function walk(root, rel = "") {
81
81
  }
82
82
  const size = out.reduce((n, f) => n + f.data.length, 0);
83
83
  if (size > 50 * 1024 * 1024)
84
- 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);
84
+ 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" });
85
85
  return out;
86
86
  }
87
87
  function pickEntry(names) {
@@ -89,15 +89,18 @@ function pickEntry(names) {
89
89
  if (names.includes(n))
90
90
  return n === "Cargo.toml" ? "src/main.rs" : n === "go.mod" ? (names.find((x) => !x.includes("/") && x.endsWith(".go")) ?? "main.go") : n;
91
91
  }
92
+ for (const n of ["index.ts", "handler.ts", "app.ts"])
93
+ if (names.includes(n))
94
+ return n;
92
95
  const top = names.filter((n) => !n.includes("/"));
93
- const guess = top.find((n) => /\.(py|m?js|cjs|rb|go)$/.test(n));
96
+ const guess = top.find((n) => /\.(py|m?js|cjs|rb|go|ts)$/.test(n) && !n.endsWith(".d.ts"));
94
97
  if (!guess)
95
- fail("No function file found: name it handler.py, index.mjs, lambda_function.rb, main.go (or pass a file)", 2);
98
+ 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" });
96
99
  return guess;
97
100
  }
98
101
  /** The handler (module.function) from the source, as Lambda names it. */
99
102
  export function findHandler(lang, entry, text) {
100
- const mod = entry.replace(/\.(py|m?js|cjs|rb)$/, "");
103
+ const mod = entry.replace(/\.(py|m?js|cjs|rb|ts|mts|cts)$/, "");
101
104
  if (lang === "python") {
102
105
  const names = [...text.matchAll(/^(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)/gm)].map((m) => m[1]);
103
106
  const fn = ["lambda_handler", "handler", "main"].find((n) => names.includes(n)) ?? names[0] ?? "lambda_handler";
@@ -181,7 +184,7 @@ async function resolveRegion(flag) {
181
184
  return all.includes("us-east-1") ? "us-east-1" : all[0] ?? "us-east-1";
182
185
  const r = REGION_ALIASES[flag] ?? flag;
183
186
  if (all.length && !all.includes(r))
184
- fail(`Lizard Functions runs in ${all.join(", ")} (aliases: us, eu); not in ${flag}`, 2);
187
+ fail(`Lizard Functions runs in ${all.join(", ")} (aliases: us, eu); not in ${flag}`, 3, "INVALID_INPUT");
185
188
  return r;
186
189
  }
187
190
  async function accounts(projectId) {
@@ -269,7 +272,7 @@ function parseEnv(list) {
269
272
  for (const kv of list) {
270
273
  const i = kv.indexOf("=");
271
274
  if (i < 1)
272
- fail(`--env takes KEY=VALUE (got ${kv})`, 2);
275
+ fail(`--env takes KEY=VALUE (got ${kv})`, 3, "INVALID_INPUT");
273
276
  out[kv.slice(0, i)] = kv.slice(i + 1);
274
277
  }
275
278
  return out;
@@ -300,17 +303,22 @@ Examples:
300
303
  lizard fn ls
301
304
  eval "$(lizard fn env)" # AWS SDK / CLI credentials and endpoint`);
302
305
  fn.command("deploy")
303
- .description("Create or update a function from a file, a directory or stdin (-); installs packages, waits until it is ready")
306
+ .description("Create or update a function from a file, a directory or stdin (-): packages, build, start check, URL, schedule; waits until it is ready")
304
307
  .argument("[path]", "file, directory or - for stdin", ".")
305
308
  .option("--name <name>", "function name (default: from the file or directory)")
306
309
  .option("--runtime <runtime>", "e.g. python3.13, nodejs22.x, ruby3.3, provided.al2023 (default: from the source)")
307
310
  .option("--handler <handler>", "e.g. app.handler (default: found in the source)")
308
- .option("--packages <list...>", "libraries to preinstall, e.g. requests numpy==2.1.3 (comma or space separated)")
311
+ .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")
312
+ .option("--no-infer", "don't install packages from the imports when none are declared")
309
313
  .option("--env <KEY=VALUE...>", "environment variables")
310
314
  .option("--memory <mb>", "memory in MB", (v) => parseInt(v, 10))
311
315
  .option("--timeout <seconds>", "timeout in seconds", (v) => parseInt(v, 10))
312
- .option("--url", "give it a public HTTPS URL")
313
- .option("--schedule <expression>", 'run it on a schedule: "rate(5 minutes)" or "cron(0 9 * * ? *)"')
316
+ .option("--url", "give it a public HTTPS URL (default: on for handlers that read HTTP events)")
317
+ .option("--no-url", "no URL")
318
+ .option("--auth <mode>", "URL access: none (public, default) or key (requests must be signed with an access key)")
319
+ .option("--schedule <when>", 'run it on a schedule: "every hour", "daily at 09:00", "*/5 * * * *", rate(...) or cron(...); "off" removes it')
320
+ .option("--test [event]", "after deploying, call it with this event (default {} / GET / for URL functions) and fail if it errors")
321
+ .option("--no-check", "skip the start check (the new code takes traffic without being started first)")
314
322
  .option("--region <region>", "us-east-1 (us) or eu-west-lim-a (eu)")
315
323
  .option("--project <id>", "project (default: the linked one)")
316
324
  .action(async (p, o) => {
@@ -318,132 +326,134 @@ Examples:
318
326
  tStart = t0;
319
327
  const stdin = p === "-" ? fs.readFileSync(0, "utf8") : undefined;
320
328
  if (p !== "-" && !fs.existsSync(p))
321
- fail(`${p} does not exist`, 2);
329
+ failEnv({ code: "INVALID_INPUT", error: `${p} does not exist`, remediation: "lizard fn deploy <file or directory> --json" }, 3);
322
330
  if (stdin !== undefined && !o.name)
323
- fail("--name is required with stdin", 2);
324
- const src = detectSource(p, { runtime: o.runtime, handler: o.handler, stdin });
331
+ failEnv({ code: "INVALID_INPUT", error: "--name is required with stdin", remediation: "echo '...' | lizard fn deploy - --name <name> --runtime python3.13 --json" }, 3);
332
+ let src;
333
+ try {
334
+ src = detectSource(p, { runtime: o.runtime, handler: o.handler, stdin });
335
+ }
336
+ catch (e) {
337
+ failEnv({ code: e.code || "INVALID_INPUT", error: e.message, remediation: e.remediation || "lizard fn deploy <path> --runtime python3.13 --json" }, 3);
338
+ }
325
339
  const name = o.name ?? defaultName(p, src);
326
340
  if (!/^[A-Za-z0-9_-]{1,64}$/.test(name))
327
- fail(`Function name ${name}: letters, numbers, hyphens and underscores, up to 64 (pass --name)`, 2);
341
+ 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);
328
342
  const runtime = o.runtime && !/^(go|rust)$/.test(o.runtime) ? o.runtime : DEFAULT_RUNTIME[src.lang];
329
- const packages = splitList(o.packages);
330
343
  const { projectId } = await resolveProjectScope(o.project);
331
344
  const region = await resolveRegion(o.region);
332
345
  status(`account in ${region}…`);
333
346
  const acct = (await accountFor(projectId, region, true));
334
- const zipBuf = zipFiles(src.files);
335
- const zip = zipBuf.toString("base64");
336
- const zipSha = createHash("sha256").update(zipBuf).digest("base64");
337
- const config = { Runtime: runtime, Handler: src.handler };
347
+ const body = { ZipFile: zipFiles(src.files).toString("base64"), Runtime: runtime, Handler: src.handler };
348
+ if (o.packages !== undefined)
349
+ body.Packages = splitList(o.packages);
350
+ if (o.infer === false)
351
+ body.Infer = false;
352
+ if (o.check === false)
353
+ body.Check = false;
338
354
  if (o.memory)
339
- config.MemorySize = o.memory;
355
+ body.MemorySize = o.memory;
340
356
  if (o.timeout)
341
- config.Timeout = o.timeout;
357
+ body.Timeout = o.timeout;
342
358
  const env = parseEnv(o.env);
343
359
  if (env)
344
- config.Environment = { Variables: env };
345
- const existing = await getFn(acct, name);
346
- const compiled = src.lang === "go" || src.lang === "rust";
347
- let created = false;
348
- // Code: built on Lizard when it has a dependency file (or is Go / Rust), else sent as is.
349
- if (src.deps || compiled) {
350
- status(existing ? "building…" : "creating (building)…");
351
- if (existing)
352
- await waitReady(acct, name);
353
- if (existing)
354
- await aws(acct, "PUT", `${fnPath(name)}/configuration`, config);
355
- if (existing)
356
- await waitReady(acct, name);
357
- const job = (await aws(acct, "POST", `lizard/functions/${encodeURIComponent(name)}/build`, {
358
- ZipFile: zip, Runtime: runtime, ...(compiled && packages.length ? { Packages: packages } : {}),
359
- ...(existing ? {} : { Create: { Role: "arn:aws:iam::000000000000:role/lizard-function", MemorySize: 512, Timeout: 30, ...config } }),
360
- })).data;
361
- const b = await waitBuild(acct, job.BuildId, status);
362
- if (b.Status !== "Succeeded") {
363
- statusDone();
364
- fail(`Build failed: ${b.Error}\n${String(b.Log || "").slice(-3000)}`, 1, "BUILD_FAILED");
365
- }
366
- created = !existing;
360
+ body.Environment = { Variables: env };
361
+ // --url / --no-url / default: "auto" (the service decides from the handler).
362
+ if (process.argv.includes("--no-url"))
363
+ body.Url = false;
364
+ else if (process.argv.includes("--url"))
365
+ body.Url = true;
366
+ if (o.auth) {
367
+ if (!["none", "key", "public", "iam"].includes(o.auth))
368
+ failEnv({ code: "INVALID_INPUT", error: "--auth is none or key", remediation: `lizard fn deploy ${p} --auth key --json` }, 3);
369
+ body.UrlAuth = ["key", "iam"].includes(o.auth) ? "AWS_IAM" : "NONE";
370
+ if (!body.Url)
371
+ body.Url = true;
367
372
  }
368
- else if (existing) {
369
- // Only what changed is sent: the same code (by SHA-256) and the same settings are no-ops.
370
- const c = existing.Configuration ?? {};
371
- if (c.LastUpdateStatus === "InProgress")
372
- await waitReady(acct, name);
373
- if (c.CodeSha256 !== zipSha) {
374
- status("updating code…");
375
- await aws(acct, "PUT", `${fnPath(name)}/code`, { ZipFile: zip });
376
- }
377
- const changed = Object.entries(config).some(([k, v]) => JSON.stringify(k === "Environment" ? { Variables: c.Environment?.Variables ?? {} } : c[k]) !== JSON.stringify(v));
378
- if (changed) {
379
- status("updating settings…");
380
- await waitReady(acct, name);
381
- await aws(acct, "PUT", `${fnPath(name)}/configuration`, config);
382
- }
373
+ if (o.schedule !== undefined)
374
+ body.Schedule = /^(off|none|no)$/i.test(o.schedule) ? "" : o.schedule;
375
+ status("deploying…");
376
+ let start;
377
+ try {
378
+ start = (await aws(acct, "POST", `lizard/functions/${encodeURIComponent(name)}/deploy`, body)).data;
383
379
  }
384
- else {
385
- status("creating…");
386
- 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 } });
387
- created = true;
380
+ catch (e) {
381
+ if (e instanceof APIError && e.status === 400)
382
+ 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);
383
+ if (e instanceof APIError && e.status === 409)
384
+ failEnv({ code: "BUSY", error: e.message, remediation: `lizard fn deploy ${p} --json` }, 1);
385
+ throw e;
388
386
  }
389
- // Packages (Node.js / Python / Ruby): the function's own layer, rebuilt only when the list changes.
390
- let installed = null;
391
- if (!compiled) {
392
- 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…"));
393
- const cur = (await aws(acct, "GET", `lizard/functions/${encodeURIComponent(name)}/packages`)).data;
394
- const same = JSON.stringify([...(cur.Packages ?? [])].sort()) === JSON.stringify([...packages].sort());
395
- if (o.packages !== undefined && !same) {
396
- status("installing packages…");
397
- const job = (await aws(acct, "PUT", `lizard/functions/${encodeURIComponent(name)}/packages`, { Packages: packages })).data;
398
- if (job.BuildId) {
399
- const b = await waitBuild(acct, job.BuildId, status);
400
- if (b.Status !== "Succeeded") {
401
- statusDone();
402
- fail(`Installing packages failed: ${b.Error}\n${String(b.Log || "").slice(-3000)}`, 1, "BUILD_FAILED");
403
- }
404
- }
405
- }
406
- installed = o.packages !== undefined ? packages : cur.Packages ?? [];
387
+ let d;
388
+ const end = Date.now() + 20 * 60_000;
389
+ for (;;) {
390
+ d = (await aws(acct, "GET", `lizard/deploys/${start.deployId}`)).data;
391
+ if (d.status !== "deploying")
392
+ break;
393
+ status({ prepare: "preparing…", build: "building…", packages: "installing packages…", check: "starting the new code…" }[d.phase] ?? "deploying…");
394
+ if (Date.now() > end)
395
+ failEnv({ code: "TIMEOUT", error: "The deploy did not finish in 20 minutes", remediation: `lizard fn deploy ${p} --json` }, 4);
396
+ await sleep(500);
407
397
  }
408
- 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…"));
409
- // URL and schedule.
410
- let url = null;
411
- if (o.url) {
412
- try {
413
- url = (await aws(acct, "GET", `2021-10-31/functions/${encodeURIComponent(name)}/url`)).data.FunctionUrl;
414
- }
415
- catch (e) {
416
- if (!(e instanceof APIError && e.status === 404))
417
- throw e;
418
- url = (await aws(acct, "POST", `2021-10-31/functions/${encodeURIComponent(name)}/url`, { AuthType: "NONE", Cors: { AllowOrigins: ["*"] } })).data.FunctionUrl;
419
- }
398
+ statusDone();
399
+ const where = o.region ? ` --region ${region}` : "";
400
+ if (d.status !== "ready") {
401
+ failEnv({ ...d, phase: d.phase, remediation: remediationFor(d, p, src, o), next: undefined }, 1);
420
402
  }
421
- if (o.schedule) {
422
- const body = { ScheduleExpression: o.schedule, FlexibleTimeWindow: { Mode: "OFF" }, Target: { Arn: cfg.FunctionArn, RoleArn: "arn:aws:iam::000000000000:role/lizard-scheduler" }, State: "ENABLED" };
423
- try {
424
- await aws(acct, "PUT", `schedules/${encodeURIComponent(name)}`, body);
403
+ // --test: call it now (a URL function gets a GET / unless an event is given).
404
+ let test = null;
405
+ if (o.test !== undefined) {
406
+ status("testing…");
407
+ if (d.url?.value && o.test === true) {
408
+ const r = await fetch(d.url.value, { signal: AbortSignal.timeout(60_000) }).catch((e) => ({ ok: false, status: 0, text: async () => String(e) }));
409
+ const text = await r.text();
410
+ test = { kind: "http", request: "GET /", status: r.status, ok: r.status > 0 && r.status < 500, body: text.slice(0, 2000) };
425
411
  }
426
- catch (e) {
427
- if (e instanceof APIError && e.status === 404)
428
- await aws(acct, "POST", `schedules/${encodeURIComponent(name)}`, body);
429
- else
430
- throw e;
412
+ else {
413
+ let ev = {};
414
+ if (typeof o.test === "string") {
415
+ try {
416
+ ev = JSON.parse(o.test);
417
+ }
418
+ catch {
419
+ failEnv({ code: "INVALID_INPUT", error: "--test takes event JSON", remediation: `lizard fn deploy ${p} --test '{}' --json` }, 3);
420
+ }
421
+ }
422
+ const r = await aws(acct, "POST", `${fnPath(name)}/invocations`, ev, { headers: { "x-amz-log-type": "Tail" } });
423
+ const err = r.headers.get("x-amz-function-error");
424
+ const tail = r.headers.get("x-amz-log-result");
425
+ test = { kind: "invoke", ok: !err, error: err || undefined, result: r.data ?? null, logTail: tail ? Buffer.from(tail, "base64").toString("utf8").slice(-3000) : undefined };
431
426
  }
427
+ statusDone();
428
+ if (!test.ok)
429
+ failEnv({ schemaVersion: 1, status: "failed", phase: "test", code: "TEST_FAILED", name, region, version: d.version,
430
+ error: test.kind === "http" ? `GET / answered ${test.status}` : `The test invocation raised ${test.error}`, test, remediation: `lizard fn logs ${name}${where} --since 5m --json`,
431
+ serving: { version: d.version, unchanged: false } }, 1);
432
432
  }
433
- statusDone();
434
- const secs = ((Date.now() - t0) / 1000).toFixed(1);
435
- const out = { name, region, created, runtime: cfg.Runtime, handler: cfg.Handler, language: src.lang, arn: cfg.FunctionArn, packages: installed, url, schedule: o.schedule ?? null,
436
- seconds: Number(secs), invoke: `lizard fn invoke ${name}${o.region ? ` --region ${region}` : ""} '{}'` };
433
+ const next = [
434
+ 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` },
435
+ ...(d.url?.value ? [{ label: "call the URL", command: `curl -s ${d.url.value}` }] : []),
436
+ { label: "logs", command: `lizard fn logs ${name}${where} --since 5m --json` },
437
+ ];
438
+ 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,
439
+ packages: d.packages, check: d.check, test, url: d.url ?? null, schedule: d.schedule ?? null, seconds: Number(((Date.now() - t0) / 1000).toFixed(1)), next };
437
440
  if (isJSONMode())
438
441
  return printJSON(out);
439
- success(`${created ? "Created" : "Updated"} ${chalk.bold(name)} in ${region} (${cfg.Runtime}, ${cfg.Handler}) in ${secs}s`);
440
- if (installed?.length)
441
- info(`Packages: ${installed.join(" ")}`);
442
- if (url)
443
- info(`URL: ${chalk.cyan(url)}`);
444
- if (o.schedule)
445
- info(`Schedule: ${o.schedule}`);
446
- info(`Call it: ${chalk.cyan(out.invoke)}`);
442
+ const pk = d.packages ?? {};
443
+ const resolved = pk.resolved ? Object.entries(pk.resolved).map(([k, v]) => `${k} ${v}`).join(", ") : (pk.requested ?? []).join(", ");
444
+ const srcLabel = { file: "from the dependency file", flag: "from --packages", imports: "from the imports", none: "" }[pk.source] ?? "";
445
+ if (pk.source !== "none" && resolved)
446
+ console.log(`${chalk.dim("Packages ")} ${resolved} ${chalk.dim(`(${srcLabel}${pk.cache === "hit" ? ", cached" : pk.installSeconds ? `, installed in ${pk.installSeconds}s` : ""})`)}`);
447
+ 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`);
448
+ if (d.check?.kind === "start")
449
+ console.log(`${chalk.dim("Checked ")} module loads and handler found${d.check.coldStartMs ? ` (cold start ${d.check.coldStartMs} ms)` : ""}`);
450
+ if (test)
451
+ console.log(`${chalk.dim("Tested ")} ${test.kind === "http" ? `GET / -> ${test.status}` : "invoked, no error"}`);
452
+ if (d.url?.value)
453
+ 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"}`);
454
+ if (d.schedule)
455
+ 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] ?? "-"}`);
456
+ console.log(`${chalk.dim("Next ")} ${next.map((n) => n.command).join("\n ")}`);
447
457
  });
448
458
  fn.command("invoke")
449
459
  .description("Call a function and print its result (and its log with --logs)")
@@ -451,6 +461,7 @@ Examples:
451
461
  .argument("[event]", "event JSON (default {}; - reads stdin)", "{}")
452
462
  .option("--logs", "print the invocation's log")
453
463
  .option("--async", "queue it (InvocationType Event) and return at once")
464
+ .option("--as-schedule", "send the event its schedule sends (run a scheduled job now)")
454
465
  .option("--region <region>").option("--project <id>")
455
466
  .action(async (name, event, o) => {
456
467
  const acct = await existingAccount(o, name);
@@ -460,7 +471,18 @@ Examples:
460
471
  parsed = JSON.parse(body);
461
472
  }
462
473
  catch {
463
- fail("The event must be JSON", 2);
474
+ fail("The event must be JSON", 3, "INVALID_INPUT");
475
+ }
476
+ if (o.asSchedule) {
477
+ // EventBridge Scheduler's event for a function, as `lizard fn deploy --schedule` sets it.
478
+ const s = await aws(acct, "GET", `schedules/${encodeURIComponent(name)}`).catch(() => null);
479
+ let input = { source: "lizard.schedule", "detail-type": "Scheduled Event", detail: {} };
480
+ try {
481
+ if (s?.data?.Target?.Input)
482
+ input = JSON.parse(s.data.Target.Input);
483
+ }
484
+ catch { /* default */ }
485
+ parsed = { ...input, time: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), id: crypto.randomUUID() };
464
486
  }
465
487
  const r = await aws(acct, "POST", `${fnPath(name)}/invocations`, parsed, { headers: { "x-amz-log-type": "Tail", ...(o.async ? { "x-amz-invocation-type": "Event" } : {}) } });
466
488
  const err = r.headers.get("x-amz-function-error");
@@ -468,7 +490,7 @@ Examples:
468
490
  const logs = tail ? Buffer.from(tail, "base64").toString("utf8") : "";
469
491
  if (isJSONMode()) {
470
492
  if (err)
471
- process.exitCode = 1;
493
+ process.exitCode = EXIT.FAILED;
472
494
  return printJSON({ status: o.async ? "queued" : err ? "error" : "ok", error: err || undefined, result: r.data ?? null, logs: o.logs ? logs : undefined });
473
495
  }
474
496
  if (o.logs && logs)
@@ -592,6 +614,43 @@ Examples:
592
614
  warn(`Created an access key for this project (saved in ${file}; Access keys in the dashboard lists and deletes keys).`);
593
615
  });
594
616
  }
617
+ // One table of exit codes for the whole CLI: 0 ok, 1 build/check/test failure, 2 authentication,
618
+ // 3 invalid input or not found, 4 timeout.
619
+ export const EXIT = { OK: 0, FAILED: 1, AUTH: 2, INVALID: 3, TIMEOUT: 4 };
620
+ /** A failure for people and agents: stdout empty, one JSON envelope on stderr (--json / no TTY), or readable text. */
621
+ function failEnv(e, exit) {
622
+ statusDone();
623
+ const env = { schemaVersion: 1, status: "failed", ...e };
624
+ for (const k of Object.keys(env))
625
+ if (env[k] === undefined || k === "deployId" || k === "log" || k === "startedAt" || k === "endedAt")
626
+ delete env[k];
627
+ if (isJSONMode())
628
+ process.stderr.write(JSON.stringify(env, null, 2) + "\n");
629
+ else {
630
+ process.stderr.write(chalk.red(`Error (${env.code}): ${env.error}\n`));
631
+ if (env.serving?.unchanged)
632
+ process.stderr.write(chalk.dim(`Version ${env.serving.version} is still serving: nothing changed.\n`));
633
+ if (env.logTail)
634
+ process.stderr.write(chalk.dim(String(env.logTail).trim().split("\n").slice(-12).join("\n") + "\n"));
635
+ if (env.remediation)
636
+ process.stderr.write(`Fix: ${chalk.cyan(env.remediation)}\n`);
637
+ }
638
+ process.exit(exit);
639
+ }
640
+ /** The exact command that fixes a failed deploy (every one is a command the CLI's tests run). */
641
+ function remediationFor(d, p, src, o) {
642
+ const base = `lizard fn deploy ${p}${o.name ? ` --name ${o.name}` : ""}${o.region ? ` --region ${o.region}` : ""}`;
643
+ const have = d.packages?.requested ?? splitList(o.packages);
644
+ switch (d.code) {
645
+ 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`;
646
+ case "HANDLER_NOT_FOUND": return d.candidates?.length ? `${base} --handler ${d.candidates[0]} --json` : `${base} --handler <module>.<function> --json`;
647
+ case "PACKAGES_CONFLICT": return `${base} --json # list packages in ${d.packages?.file ?? "the dependency file"} only (drop --packages)`;
648
+ case "AMBIGUOUS_IMPORT": return `${base} --packages <the package you need, e.g. ${String(d.ambiguous?.[0]?.choices ?? "").split(",")[0].trim()}> --json`;
649
+ 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`;
650
+ case "INVALID_SCHEDULE": return `${base} --schedule "every hour" --json`;
651
+ default: return `${base} --json`;
652
+ }
653
+ }
595
654
  function defaultName(p, src) {
596
655
  const base = p === "." ? path.basename(process.cwd()) : fs.existsSync(p) && fs.statSync(p).isDirectory() ? path.basename(path.resolve(p)) : path.basename(p).replace(/\.[^.]+$/, "");
597
656
  const n = (["handler", "lambda_function", "index", "main", "app", "bootstrap"].includes(base) ? path.basename(path.resolve(path.dirname(p === "." ? "./x" : p))) : base)
@@ -606,7 +665,7 @@ async function existingAccount(o, name) {
606
665
  const region = await resolveRegion(o.region);
607
666
  const a = all.find((x) => x.region === region);
608
667
  if (!a)
609
- fail(`No functions in ${region} for this project`, 1, "NOT_FOUND");
668
+ fail(`No functions in ${region} for this project`, 3, "NOT_FOUND");
610
669
  return a;
611
670
  }
612
671
  const holding = [];
@@ -614,15 +673,15 @@ async function existingAccount(o, name) {
614
673
  if (await getFn(a, name).catch(() => null))
615
674
  holding.push(a);
616
675
  if (!holding.length)
617
- fail(`Function ${name} not found (lizard fn ls)`, 1, "NOT_FOUND");
676
+ fail(`Function ${name} not found (lizard fn ls)`, 3, "NOT_FOUND");
618
677
  if (holding.length > 1)
619
- fail(`${name} exists in ${holding.map((a) => a.region).join(" and ")}: pass --region`, 2);
678
+ fail(`${name} exists in ${holding.map((a) => a.region).join(" and ")}: pass --region`, 3, "REGION_REQUIRED");
620
679
  return holding[0];
621
680
  }
622
681
  function parseDuration(s) {
623
682
  const m = String(s).match(/^(\d+)\s*(s|m|h|d)?$/);
624
683
  if (!m)
625
- fail(`--since takes e.g. 30s, 10m, 2h, 1d (got ${s})`, 2);
684
+ fail(`--since takes e.g. 30s, 10m, 2h, 1d (got ${s})`, 3, "INVALID_INPUT");
626
685
  return Number(m[1]) * { s: 1e3, m: 6e4, h: 36e5, d: 864e5 }[m[2] ?? "m"];
627
686
  }
628
687
  //# sourceMappingURL=fn.js.map