@lizard-build/cli 4.0.98 → 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.
- package/dist/commands/fn.d.ts +7 -0
- package/dist/commands/fn.js +221 -130
- package/dist/commands/fn.js.map +1 -1
- package/dist/lib/skills-data.generated.js +1 -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/dist/lib/updater.js.map +1 -1
- package/package.json +1 -1
- package/skill-data/core/references/functions.md +61 -30
- package/src/commands/fn.ts +177 -110
- package/src/lib/updater.ts +1 -1
package/dist/commands/fn.d.ts
CHANGED
|
@@ -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
|
+
};
|
package/dist/commands/fn.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
|
+
import * as os from "node:os";
|
|
3
4
|
import * as zlib from "node:zlib";
|
|
4
|
-
import
|
|
5
|
+
import * as crypto from "node:crypto";
|
|
5
6
|
import chalk from "chalk";
|
|
6
7
|
import { api, getBaseURL, getRequestToken, clientHeaders, APIError } from "../lib/api.js";
|
|
7
8
|
import { resolveProjectScope } from "../lib/resolve.js";
|
|
@@ -38,8 +39,8 @@ export function detectSource(p, opts = {}) {
|
|
|
38
39
|
const names = files.map((f) => f.name);
|
|
39
40
|
const lang = langOfRuntime(opts.runtime) ?? (names.includes("Cargo.toml") ? "rust" : names.includes("go.mod") || entry.endsWith(".go") ? "go"
|
|
40
41
|
: /\.py$/.test(entry) ? "python" : /\.(m?js|cjs)$/.test(entry) ? "node" : /\.rb$/.test(entry) ? "ruby" : entry === "bootstrap" ? "shell"
|
|
41
|
-
: /\.ts$/.test(entry) ?
|
|
42
|
-
: (
|
|
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` }); })());
|
|
43
44
|
const text = files.find((f) => f.name === entry)?.data.toString("utf8") ?? "";
|
|
44
45
|
const handler = opts.handler ?? (lang === "go" || lang === "rust" || lang === "shell" ? "bootstrap" : findHandler(lang, entry, text));
|
|
45
46
|
const deps = names.some((n) => ["requirements.txt", "Gemfile", "go.mod", "Cargo.toml"].includes(n))
|
|
@@ -80,7 +81,7 @@ function walk(root, rel = "") {
|
|
|
80
81
|
}
|
|
81
82
|
const size = out.reduce((n, f) => n + f.data.length, 0);
|
|
82
83
|
if (size > 50 * 1024 * 1024)
|
|
83
|
-
|
|
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" });
|
|
84
85
|
return out;
|
|
85
86
|
}
|
|
86
87
|
function pickEntry(names) {
|
|
@@ -88,15 +89,18 @@ function pickEntry(names) {
|
|
|
88
89
|
if (names.includes(n))
|
|
89
90
|
return n === "Cargo.toml" ? "src/main.rs" : n === "go.mod" ? (names.find((x) => !x.includes("/") && x.endsWith(".go")) ?? "main.go") : n;
|
|
90
91
|
}
|
|
92
|
+
for (const n of ["index.ts", "handler.ts", "app.ts"])
|
|
93
|
+
if (names.includes(n))
|
|
94
|
+
return n;
|
|
91
95
|
const top = names.filter((n) => !n.includes("/"));
|
|
92
|
-
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"));
|
|
93
97
|
if (!guess)
|
|
94
|
-
|
|
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" });
|
|
95
99
|
return guess;
|
|
96
100
|
}
|
|
97
101
|
/** The handler (module.function) from the source, as Lambda names it. */
|
|
98
102
|
export function findHandler(lang, entry, text) {
|
|
99
|
-
const mod = entry.replace(/\.(py|m?js|cjs|rb)$/, "");
|
|
103
|
+
const mod = entry.replace(/\.(py|m?js|cjs|rb|ts|mts|cts)$/, "");
|
|
100
104
|
if (lang === "python") {
|
|
101
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]);
|
|
102
106
|
const fn = ["lambda_handler", "handler", "main"].find((n) => names.includes(n)) ?? names[0] ?? "lambda_handler";
|
|
@@ -180,7 +184,7 @@ async function resolveRegion(flag) {
|
|
|
180
184
|
return all.includes("us-east-1") ? "us-east-1" : all[0] ?? "us-east-1";
|
|
181
185
|
const r = REGION_ALIASES[flag] ?? flag;
|
|
182
186
|
if (all.length && !all.includes(r))
|
|
183
|
-
fail(`Lizard Functions runs in ${all.join(", ")} (aliases: us, eu); not in ${flag}`,
|
|
187
|
+
fail(`Lizard Functions runs in ${all.join(", ")} (aliases: us, eu); not in ${flag}`, 3, "INVALID_INPUT");
|
|
184
188
|
return r;
|
|
185
189
|
}
|
|
186
190
|
async function accounts(projectId) {
|
|
@@ -268,7 +272,7 @@ function parseEnv(list) {
|
|
|
268
272
|
for (const kv of list) {
|
|
269
273
|
const i = kv.indexOf("=");
|
|
270
274
|
if (i < 1)
|
|
271
|
-
fail(`--env takes KEY=VALUE (got ${kv})`,
|
|
275
|
+
fail(`--env takes KEY=VALUE (got ${kv})`, 3, "INVALID_INPUT");
|
|
272
276
|
out[kv.slice(0, i)] = kv.slice(i + 1);
|
|
273
277
|
}
|
|
274
278
|
return out;
|
|
@@ -299,17 +303,22 @@ Examples:
|
|
|
299
303
|
lizard fn ls
|
|
300
304
|
eval "$(lizard fn env)" # AWS SDK / CLI credentials and endpoint`);
|
|
301
305
|
fn.command("deploy")
|
|
302
|
-
.description("Create or update a function from a file, a directory or stdin (-)
|
|
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")
|
|
303
307
|
.argument("[path]", "file, directory or - for stdin", ".")
|
|
304
308
|
.option("--name <name>", "function name (default: from the file or directory)")
|
|
305
309
|
.option("--runtime <runtime>", "e.g. python3.13, nodejs22.x, ruby3.3, provided.al2023 (default: from the source)")
|
|
306
310
|
.option("--handler <handler>", "e.g. app.handler (default: found in the source)")
|
|
307
|
-
.option("--packages <list...>", "libraries
|
|
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")
|
|
308
313
|
.option("--env <KEY=VALUE...>", "environment variables")
|
|
309
314
|
.option("--memory <mb>", "memory in MB", (v) => parseInt(v, 10))
|
|
310
315
|
.option("--timeout <seconds>", "timeout in seconds", (v) => parseInt(v, 10))
|
|
311
|
-
.option("--url", "give it a public HTTPS URL")
|
|
312
|
-
.option("--
|
|
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)")
|
|
313
322
|
.option("--region <region>", "us-east-1 (us) or eu-west-lim-a (eu)")
|
|
314
323
|
.option("--project <id>", "project (default: the linked one)")
|
|
315
324
|
.action(async (p, o) => {
|
|
@@ -317,132 +326,134 @@ Examples:
|
|
|
317
326
|
tStart = t0;
|
|
318
327
|
const stdin = p === "-" ? fs.readFileSync(0, "utf8") : undefined;
|
|
319
328
|
if (p !== "-" && !fs.existsSync(p))
|
|
320
|
-
|
|
329
|
+
failEnv({ code: "INVALID_INPUT", error: `${p} does not exist`, remediation: "lizard fn deploy <file or directory> --json" }, 3);
|
|
321
330
|
if (stdin !== undefined && !o.name)
|
|
322
|
-
|
|
323
|
-
|
|
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
|
+
}
|
|
324
339
|
const name = o.name ?? defaultName(p, src);
|
|
325
340
|
if (!/^[A-Za-z0-9_-]{1,64}$/.test(name))
|
|
326
|
-
|
|
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);
|
|
327
342
|
const runtime = o.runtime && !/^(go|rust)$/.test(o.runtime) ? o.runtime : DEFAULT_RUNTIME[src.lang];
|
|
328
|
-
const packages = splitList(o.packages);
|
|
329
343
|
const { projectId } = await resolveProjectScope(o.project);
|
|
330
344
|
const region = await resolveRegion(o.region);
|
|
331
345
|
status(`account in ${region}…`);
|
|
332
346
|
const acct = (await accountFor(projectId, region, true));
|
|
333
|
-
const
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
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;
|
|
337
354
|
if (o.memory)
|
|
338
|
-
|
|
355
|
+
body.MemorySize = o.memory;
|
|
339
356
|
if (o.timeout)
|
|
340
|
-
|
|
357
|
+
body.Timeout = o.timeout;
|
|
341
358
|
const env = parseEnv(o.env);
|
|
342
359
|
if (env)
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
if (
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
await waitReady(acct, name);
|
|
356
|
-
const job = (await aws(acct, "POST", `lizard/functions/${encodeURIComponent(name)}/build`, {
|
|
357
|
-
ZipFile: zip, Runtime: runtime, ...(compiled && packages.length ? { Packages: packages } : {}),
|
|
358
|
-
...(existing ? {} : { Create: { Role: "arn:aws:iam::000000000000:role/lizard-function", MemorySize: 512, Timeout: 30, ...config } }),
|
|
359
|
-
})).data;
|
|
360
|
-
const b = await waitBuild(acct, job.BuildId, status);
|
|
361
|
-
if (b.Status !== "Succeeded") {
|
|
362
|
-
statusDone();
|
|
363
|
-
fail(`Build failed: ${b.Error}\n${String(b.Log || "").slice(-3000)}`, 1, "BUILD_FAILED");
|
|
364
|
-
}
|
|
365
|
-
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;
|
|
366
372
|
}
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
status("updating code…");
|
|
374
|
-
await aws(acct, "PUT", `${fnPath(name)}/code`, { ZipFile: zip });
|
|
375
|
-
}
|
|
376
|
-
const changed = Object.entries(config).some(([k, v]) => JSON.stringify(k === "Environment" ? { Variables: c.Environment?.Variables ?? {} } : c[k]) !== JSON.stringify(v));
|
|
377
|
-
if (changed) {
|
|
378
|
-
status("updating settings…");
|
|
379
|
-
await waitReady(acct, name);
|
|
380
|
-
await aws(acct, "PUT", `${fnPath(name)}/configuration`, config);
|
|
381
|
-
}
|
|
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;
|
|
382
379
|
}
|
|
383
|
-
|
|
384
|
-
status
|
|
385
|
-
|
|
386
|
-
|
|
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;
|
|
387
386
|
}
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
await
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
const b = await waitBuild(acct, job.BuildId, status);
|
|
399
|
-
if (b.Status !== "Succeeded") {
|
|
400
|
-
statusDone();
|
|
401
|
-
fail(`Installing packages failed: ${b.Error}\n${String(b.Log || "").slice(-3000)}`, 1, "BUILD_FAILED");
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
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);
|
|
406
397
|
}
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
try {
|
|
412
|
-
url = (await aws(acct, "GET", `2021-10-31/functions/${encodeURIComponent(name)}/url`)).data.FunctionUrl;
|
|
413
|
-
}
|
|
414
|
-
catch (e) {
|
|
415
|
-
if (!(e instanceof APIError && e.status === 404))
|
|
416
|
-
throw e;
|
|
417
|
-
url = (await aws(acct, "POST", `2021-10-31/functions/${encodeURIComponent(name)}/url`, { AuthType: "NONE", Cors: { AllowOrigins: ["*"] } })).data.FunctionUrl;
|
|
418
|
-
}
|
|
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);
|
|
419
402
|
}
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
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) };
|
|
424
411
|
}
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
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 };
|
|
430
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);
|
|
431
432
|
}
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
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 };
|
|
436
440
|
if (isJSONMode())
|
|
437
441
|
return printJSON(out);
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
if (
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
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 ")}`);
|
|
446
457
|
});
|
|
447
458
|
fn.command("invoke")
|
|
448
459
|
.description("Call a function and print its result (and its log with --logs)")
|
|
@@ -450,6 +461,7 @@ Examples:
|
|
|
450
461
|
.argument("[event]", "event JSON (default {}; - reads stdin)", "{}")
|
|
451
462
|
.option("--logs", "print the invocation's log")
|
|
452
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)")
|
|
453
465
|
.option("--region <region>").option("--project <id>")
|
|
454
466
|
.action(async (name, event, o) => {
|
|
455
467
|
const acct = await existingAccount(o, name);
|
|
@@ -459,7 +471,18 @@ Examples:
|
|
|
459
471
|
parsed = JSON.parse(body);
|
|
460
472
|
}
|
|
461
473
|
catch {
|
|
462
|
-
fail("The event must be JSON",
|
|
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() };
|
|
463
486
|
}
|
|
464
487
|
const r = await aws(acct, "POST", `${fnPath(name)}/invocations`, parsed, { headers: { "x-amz-log-type": "Tail", ...(o.async ? { "x-amz-invocation-type": "Event" } : {}) } });
|
|
465
488
|
const err = r.headers.get("x-amz-function-error");
|
|
@@ -467,7 +490,7 @@ Examples:
|
|
|
467
490
|
const logs = tail ? Buffer.from(tail, "base64").toString("utf8") : "";
|
|
468
491
|
if (isJSONMode()) {
|
|
469
492
|
if (err)
|
|
470
|
-
process.exitCode =
|
|
493
|
+
process.exitCode = EXIT.FAILED;
|
|
471
494
|
return printJSON({ status: o.async ? "queued" : err ? "error" : "ok", error: err || undefined, result: r.data ?? null, logs: o.logs ? logs : undefined });
|
|
472
495
|
}
|
|
473
496
|
if (o.logs && logs)
|
|
@@ -545,21 +568,89 @@ Examples:
|
|
|
545
568
|
});
|
|
546
569
|
fn.command("env")
|
|
547
570
|
.description("Print AWS credentials and endpoints for the project's functions (for the AWS SDKs / CLI): eval \"$(lizard fn env)\"")
|
|
571
|
+
.option("--new", "create a new access key instead of reusing this machine's")
|
|
548
572
|
.option("--region <region>").option("--project <id>")
|
|
549
573
|
.action(async (o) => {
|
|
550
574
|
const { projectId } = await resolveProjectScope(o.project);
|
|
551
575
|
const region = await resolveRegion(o.region);
|
|
552
576
|
await accountFor(projectId, region, true);
|
|
553
|
-
|
|
577
|
+
// One key per project on this machine, reused (eval'd in a shell profile, a key per run
|
|
578
|
+
// would pile up); kept only while the project still lists it.
|
|
579
|
+
const file = path.join(os.homedir(), ".lizard", "functions-keys.json");
|
|
580
|
+
let saved = {};
|
|
581
|
+
try {
|
|
582
|
+
saved = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
583
|
+
}
|
|
584
|
+
catch {
|
|
585
|
+
saved = {};
|
|
586
|
+
}
|
|
587
|
+
let k = o.new ? null : saved[projectId] ?? null;
|
|
588
|
+
if (k) {
|
|
589
|
+
const live = await api.get(`/api/functions/projects/${encodeURIComponent(projectId)}/keys`).catch(() => null);
|
|
590
|
+
if (!live?.keys?.some((x) => x.accessKeyId === k.accessKeyId))
|
|
591
|
+
k = null;
|
|
592
|
+
else
|
|
593
|
+
k.endpoints = live.endpoints ?? k.endpoints;
|
|
594
|
+
}
|
|
595
|
+
let created = false;
|
|
596
|
+
if (!k) {
|
|
597
|
+
k = await api.post(`/api/functions/projects/${encodeURIComponent(projectId)}/keys`);
|
|
598
|
+
saved[projectId] = { accessKeyId: k.accessKeyId, secretAccessKey: k.secretAccessKey, endpoints: k.endpoints };
|
|
599
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
600
|
+
fs.writeFileSync(file, JSON.stringify(saved, null, 2), { mode: 0o600 });
|
|
601
|
+
created = true;
|
|
602
|
+
}
|
|
554
603
|
const ep = k.endpoints?.[region];
|
|
555
|
-
if (
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
if (process.
|
|
560
|
-
|
|
604
|
+
if (!ep)
|
|
605
|
+
fail(`No Functions endpoint for ${region}`, 1);
|
|
606
|
+
const sh = (v) => `'${String(v).replace(/'/g, "'\\''")}'`;
|
|
607
|
+
// Shell exports by default even when stdout is a pipe: `eval "$(lizard fn env)"` is the point.
|
|
608
|
+
if (process.argv.includes("--json"))
|
|
609
|
+
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, created });
|
|
610
|
+
const vars = [["AWS_ACCESS_KEY_ID", k.accessKeyId], ["AWS_SECRET_ACCESS_KEY", k.secretAccessKey], ["AWS_REGION", region], ["AWS_DEFAULT_REGION", region],
|
|
611
|
+
...["LAMBDA", "SQS", "SCHEDULER", "EVENTBRIDGE", "CLOUDWATCH_LOGS"].map((s2) => [`AWS_ENDPOINT_URL_${s2}`, ep])];
|
|
612
|
+
process.stdout.write(vars.map(([n, v]) => `export ${n}=${sh(v)}`).join("\n") + "\n");
|
|
613
|
+
if (created && process.stderr.isTTY)
|
|
614
|
+
warn(`Created an access key for this project (saved in ${file}; Access keys in the dashboard lists and deletes keys).`);
|
|
561
615
|
});
|
|
562
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
|
+
}
|
|
563
654
|
function defaultName(p, src) {
|
|
564
655
|
const base = p === "." ? path.basename(process.cwd()) : fs.existsSync(p) && fs.statSync(p).isDirectory() ? path.basename(path.resolve(p)) : path.basename(p).replace(/\.[^.]+$/, "");
|
|
565
656
|
const n = (["handler", "lambda_function", "index", "main", "app", "bootstrap"].includes(base) ? path.basename(path.resolve(path.dirname(p === "." ? "./x" : p))) : base)
|
|
@@ -574,7 +665,7 @@ async function existingAccount(o, name) {
|
|
|
574
665
|
const region = await resolveRegion(o.region);
|
|
575
666
|
const a = all.find((x) => x.region === region);
|
|
576
667
|
if (!a)
|
|
577
|
-
fail(`No functions in ${region} for this project`,
|
|
668
|
+
fail(`No functions in ${region} for this project`, 3, "NOT_FOUND");
|
|
578
669
|
return a;
|
|
579
670
|
}
|
|
580
671
|
const holding = [];
|
|
@@ -582,15 +673,15 @@ async function existingAccount(o, name) {
|
|
|
582
673
|
if (await getFn(a, name).catch(() => null))
|
|
583
674
|
holding.push(a);
|
|
584
675
|
if (!holding.length)
|
|
585
|
-
fail(`Function ${name} not found (lizard fn ls)`,
|
|
676
|
+
fail(`Function ${name} not found (lizard fn ls)`, 3, "NOT_FOUND");
|
|
586
677
|
if (holding.length > 1)
|
|
587
|
-
fail(`${name} exists in ${holding.map((a) => a.region).join(" and ")}: pass --region`,
|
|
678
|
+
fail(`${name} exists in ${holding.map((a) => a.region).join(" and ")}: pass --region`, 3, "REGION_REQUIRED");
|
|
588
679
|
return holding[0];
|
|
589
680
|
}
|
|
590
681
|
function parseDuration(s) {
|
|
591
682
|
const m = String(s).match(/^(\d+)\s*(s|m|h|d)?$/);
|
|
592
683
|
if (!m)
|
|
593
|
-
fail(`--since takes e.g. 30s, 10m, 2h, 1d (got ${s})`,
|
|
684
|
+
fail(`--since takes e.g. 30s, 10m, 2h, 1d (got ${s})`, 3, "INVALID_INPUT");
|
|
594
685
|
return Number(m[1]) * { s: 1e3, m: 6e4, h: 36e5, d: 864e5 }[m[2] ?? "m"];
|
|
595
686
|
}
|
|
596
687
|
//# sourceMappingURL=fn.js.map
|