wawesome 0.0.6 → 0.0.7

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.
Files changed (3) hide show
  1. package/README.md +25 -0
  2. package/dist/index.mjs +943 -333
  3. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -5,6 +5,7 @@ import { build } from "esbuild";
5
5
  import os from "node:os";
6
6
  import http from "node:http";
7
7
  import readline from "node:readline";
8
+ import zlib from "node:zlib";
8
9
  import { select } from "@inquirer/prompts";
9
10
  //#region src/config.ts
10
11
  /**
@@ -124,6 +125,7 @@ async function buildJs(entryInput, options) {
124
125
  try {
125
126
  await build({
126
127
  entryPoints: [entry],
128
+ absWorkingDir: process.cwd(),
127
129
  bundle: true,
128
130
  format: "esm",
129
131
  outfile: outPath,
@@ -203,27 +205,44 @@ function isInteractive() {
203
205
  return Boolean(process.stdin.isTTY);
204
206
  }
205
207
  //#endregion
206
- //#region src/tenant.ts
208
+ //#region src/errors.ts
207
209
  /** A rejection carrying the gateway's own prose and, where given, its reason. */
208
210
  var GatewayError = class extends Error {
209
211
  status;
210
212
  reason;
211
- constructor(message, status, reason) {
213
+ /** The raw response, for `--verbose` to print when the prose is not enough. */
214
+ body;
215
+ constructor(message, status, reason, body = "") {
212
216
  super(message);
213
217
  this.name = "GatewayError";
214
218
  this.status = status;
215
219
  this.reason = reason;
220
+ this.body = body;
216
221
  }
217
222
  };
223
+ /**
224
+ * Read a failed response into a `GatewayError`.
225
+ *
226
+ * `fallback` is used only when the response carries no prose of its own — a
227
+ * proxy's HTML error page, or an empty body. A 401 is deliberately *not* special
228
+ * cased here: what to say about an expired session depends on what the caller
229
+ * was doing, so callers handle it before reaching this.
230
+ */
218
231
  async function asGatewayError(res, fallback) {
219
- const body = await res.text();
232
+ const body = await res.text().catch(() => "");
220
233
  try {
221
234
  const parsed = JSON.parse(body);
222
- return new GatewayError(parsed.error || fallback, res.status, parsed.reason);
235
+ return new GatewayError(parsed.error || fallback, res.status, parsed.reason, body);
223
236
  } catch {
224
- return new GatewayError(fallback, res.status);
237
+ return new GatewayError(fallback, res.status, void 0, body);
225
238
  }
226
239
  }
240
+ /** What went wrong, as text, whatever was thrown. */
241
+ function errorText(err) {
242
+ return err instanceof Error ? err.message : String(err);
243
+ }
244
+ //#endregion
245
+ //#region src/tenant.ts
227
246
  async function fetchTenantDetails(creds) {
228
247
  const res = await fetch(`${creds.gateway_url}/v1/tenant`, { headers: { Authorization: `Bearer ${creds.tenant_jwt}` } });
229
248
  if (!res.ok) throw await asGatewayError(res, `Failed to read workspace (HTTP ${res.status}).`);
@@ -600,196 +619,957 @@ async function deploy(entryInput, options) {
600
619
  if (version !== void 0) console.log(` Version: ${version}`);
601
620
  if (invokeUrl) console.log(`\n URL: \x1b[36m${invokeUrl}\x1b[0m`);
602
621
  console.log("======================================================\n");
622
+ return {
623
+ app,
624
+ functionName: funcName,
625
+ version,
626
+ invokeUrl
627
+ };
603
628
  }
629
+ //#endregion
630
+ //#region src/env.ts
631
+ const STANDARD_SECRET_MESSAGES = [
632
+ "Encrypted at rest using AES-256",
633
+ "This value can't be viewed again after you save it — only updated or deleted",
634
+ "Only decrypted at the moment your function runs — never returned by the CLI, dashboard, or API after creation."
635
+ ];
604
636
  /**
605
- * Normalise arbitrary input into a legal DNS label, returning an empty string
606
- * when nothing legal survives — callers decide whether that is an error.
607
- */
608
- function sanitizeSlug(raw) {
609
- let label = "";
610
- for (const c of raw.trim().toLowerCase()) if (c >= "a" && c <= "z") label += c;
611
- else if (c >= "0" && c <= "9") label += c;
612
- else if (label.length > 0 && !label.endsWith("-")) label += "-";
613
- label = label.slice(0, 63);
614
- while (label.endsWith("-")) label = label.slice(0, -1);
615
- return label;
616
- }
617
- /**
618
- * Whether `candidate` is already a legal DNS label — i.e. whether
619
- * {@link sanitizeSlug} would leave it untouched.
637
+ * Load credentials and validate project config.
620
638
  */
621
- function isLegalSlug(candidate) {
622
- return candidate.length > 0 && candidate.length <= 63 && !candidate.startsWith("-") && !candidate.endsWith("-") && !candidate.includes("--") && /^[a-z0-9-]+$/.test(candidate);
639
+ function loadClientContext() {
640
+ const creds = readCredentials();
641
+ if (!creds) {
642
+ console.error("[wawesome] Error: Not logged in. Run 'wawesome login' first.");
643
+ process.exit(1);
644
+ }
645
+ const config = readFunctionConfig();
646
+ if (!config || !config.app || !config.app.trim()) {
647
+ console.error("[wawesome] Error: No wawesome-function.json found in the current directory.");
648
+ console.error("[wawesome] Run 'wawesome init' to create one, or create it manually.");
649
+ process.exit(1);
650
+ }
651
+ return {
652
+ creds,
653
+ app: config.app.trim()
654
+ };
623
655
  }
624
- //#endregion
625
- //#region src/init.ts
626
- /** Bound on the re-prompt loop, so unusable input exits instead of looping. */
627
- const MAX_APP_SLUG_ATTEMPTS = 5;
628
656
  /**
629
- * Ask which App this Function belongs to, defaulting to the directory name.
657
+ * Store one variable on an App, reporting failure by throwing.
630
658
  *
631
- * Never falls back to `default-app`, and re-offers an illegal answer as a
632
- * suggestion rather than rewriting it: the slug is part of the public URL a
633
- * client reads, so the user sees the name they will get before agreeing to it.
659
+ * The endpoint half of `env set`, without the exiting: template scaffolding
660
+ * stores a whole manifest's worth of variables and has already written files by
661
+ * the time it does, so it needs to say what did land before it gives up.
634
662
  */
635
- async function promptForAppSlug(session, dirName) {
636
- let suggestion = sanitizeSlug(dirName);
637
- for (let attempt = 0; attempt < MAX_APP_SLUG_ATTEMPTS; attempt++) {
638
- const answer = await session.ask(" App slug?", suggestion);
639
- if (isLegalSlug(answer)) return answer;
640
- const sanitized = sanitizeSlug(answer);
641
- if (sanitized) {
642
- console.log(`[wawesome] '${answer}' can't be used as an App slug. Suggested: '${sanitized}'.`);
643
- suggestion = sanitized;
644
- } else console.log("[wawesome] An App slug needs lowercase letters or numbers, separated by single hyphens.");
663
+ async function putEnvVar(creds, app, key, value, isSecret) {
664
+ const url = `${creds.gateway_url}/v1/apps/${encodeURIComponent(app)}/env`;
665
+ const res = await fetch(url, {
666
+ method: "POST",
667
+ headers: {
668
+ Authorization: `Bearer ${creds.tenant_jwt}`,
669
+ "Content-Type": "application/json"
670
+ },
671
+ body: JSON.stringify({
672
+ key,
673
+ value,
674
+ is_secret: isSecret
675
+ })
676
+ });
677
+ if (!res.ok) {
678
+ if (res.status === 401) throw new GatewayError("Authentication expired. Run 'wawesome login' again.", 401);
679
+ throw await asGatewayError(res, `Failed to set variable '${key}' (HTTP ${res.status}).`);
645
680
  }
646
- console.error(`[wawesome] Error: no usable App slug after ${MAX_APP_SLUG_ATTEMPTS} attempts. Nothing was written.`);
647
- console.error("[wawesome] Run 'wawesome init' again once you know what to call the App.");
648
- process.exit(1);
681
+ return await res.json();
649
682
  }
650
683
  /**
651
- * Scaffold a new wawesome function project in the current directory.
684
+ * Set or overwrite an environment variable on the current app.
652
685
  */
653
- async function init(options) {
686
+ async function setEnvVar(key, value, options) {
654
687
  const isVerbose = Boolean(options.verbose);
655
- const cwd = process.cwd();
656
- const dirName = path.basename(cwd);
657
- console.log("[wawesome] Initializing a new function project...\n");
658
- const session = openPromptSession();
659
- let functionName;
660
- let appSlug;
661
- try {
662
- functionName = await session.ask(" Function name?", dirName);
663
- console.log(" (an App groups the Functions of one project — its slug is part of the public URL)");
664
- appSlug = await promptForAppSlug(session, dirName);
665
- } finally {
666
- session.close();
667
- }
668
- const entry = "src/index.ts";
669
- if (isVerbose) console.log(`[wawesome:verbose] function=${functionName}, app=${appSlug}, entry=${entry}`);
670
- const configContent = {
671
- app: appSlug,
672
- function: functionName,
673
- entry
674
- };
675
- const configPath = path.join(cwd, "wawesome-function.json");
676
- if (fs.existsSync(configPath)) console.log("[wawesome] wawesome-function.json already exists, skipping.");
677
- else {
678
- fs.writeFileSync(configPath, JSON.stringify(configContent, null, 2) + "\n", "utf-8");
679
- console.log("[wawesome] ✅ Created wawesome-function.json");
680
- }
681
- const srcDir = path.join(cwd, "src");
682
- const indexPath = path.join(srcDir, "index.ts");
683
- if (fs.existsSync(indexPath)) console.log("[wawesome] src/index.ts already exists, skipping.");
684
- else {
685
- fs.mkdirSync(srcDir, { recursive: true });
686
- fs.writeFileSync(indexPath, `/**
687
- * Serverless Function Handler
688
- * Standard HTTP fetch request handler
689
- */
690
- export default {
691
- async fetch(request: Request): Promise<Response> {
692
- return Response.json({
693
- message: "Hello, World!",
694
- });
695
- },
696
- };
697
- `, "utf-8");
698
- console.log("[wawesome] ✅ Created src/index.ts");
699
- }
700
- const pkgPath = path.join(cwd, "package.json");
701
- if (fs.existsSync(pkgPath)) console.log("[wawesome] package.json already exists, skipping.");
702
- else {
703
- const pkgContent = {
704
- name: functionName,
705
- type: "module",
706
- version: "1.0.0",
707
- description: `Serverless function: ${functionName}`,
708
- scripts: {
709
- build: "wawesome build",
710
- deploy: "wawesome deploy",
711
- typecheck: "tsc --noEmit"
712
- },
713
- devDependencies: {
714
- "wawesome": "^1.0.0",
715
- typescript: "^7.0.0"
716
- }
717
- };
718
- fs.writeFileSync(pkgPath, JSON.stringify(pkgContent, null, 2) + "\n", "utf-8");
719
- console.log("[wawesome] ✅ Created package.json");
688
+ if (!key || value === void 0) {
689
+ console.error("[wawesome] Error: Missing key or value. Usage: wawesome env set <KEY> <VALUE> [--secret]");
690
+ process.exit(1);
720
691
  }
721
- const tsconfigPath = path.join(cwd, "tsconfig.json");
722
- if (fs.existsSync(tsconfigPath)) console.log("[wawesome] tsconfig.json already exists, skipping.");
723
- else {
724
- fs.writeFileSync(tsconfigPath, JSON.stringify({
725
- compilerOptions: {
726
- target: "ES2022",
727
- module: "ESNext",
728
- moduleResolution: "bundler",
729
- strict: true,
730
- noEmit: true,
731
- lib: [
732
- "ES2022",
733
- "DOM",
734
- "DOM.Iterable"
735
- ]
736
- },
737
- include: ["src"]
738
- }, null, 2) + "\n", "utf-8");
739
- console.log("[wawesome] ✅ Created tsconfig.json");
692
+ const { creds, app } = loadClientContext();
693
+ const isSecret = Boolean(options.secret);
694
+ if (isVerbose) {
695
+ console.log(`[wawesome:verbose] POST ${creds.gateway_url}/v1/apps/${encodeURIComponent(app)}/env`);
696
+ console.log(`[wawesome:verbose] Payload: key=${key}, is_secret=${isSecret}`);
740
697
  }
741
- const gitignorePath = path.join(cwd, ".gitignore");
742
- if (fs.existsSync(gitignorePath)) console.log("[wawesome] .gitignore already exists, skipping.");
743
- else {
744
- fs.writeFileSync(gitignorePath, "node_modules\ndist\n", "utf-8");
745
- console.log("[wawesome] ✅ Created .gitignore");
698
+ let data;
699
+ try {
700
+ data = await putEnvVar(creds, app, key, value, isSecret);
701
+ } catch (err) {
702
+ console.error(`[wawesome] Error: ${errorText(err)}`);
703
+ if (isVerbose && err instanceof GatewayError) console.error(`[wawesome:verbose] Response: ${err.body}`);
704
+ process.exit(1);
705
+ return;
746
706
  }
747
- console.log("\n[wawesome] 🎉 Project initialized! Next steps:");
748
- console.log(" 1. npm install");
749
- console.log(" 2. wawesome login");
750
- console.log(" 3. wawesome deploy\n");
707
+ if (data.variable.is_secret || isSecret) {
708
+ console.log(`\n[wawesome] ✅ Set secret variable '${key}' on app '${app}'.`);
709
+ const messages = data.notice?.messages?.length ? data.notice.messages : STANDARD_SECRET_MESSAGES;
710
+ console.log("\n🔒 \x1B[1mSecret Notice:\x1B[0m");
711
+ for (const msg of messages) console.log(` • ${msg}`);
712
+ console.log("");
713
+ } else console.log(`[wawesome] ✅ Set variable '${key}' on app '${app}'.`);
751
714
  }
752
- //#endregion
753
- //#region src/version.ts
754
- async function fetchVersions(gatewayUrl, tenantJwt, app, funcName, env, isVerbose) {
755
- const url = `${gatewayUrl}/v1/apps/${encodeURIComponent(app)}/functions/${encodeURIComponent(funcName)}/versions?environment=${encodeURIComponent(env)}`;
715
+ function truncate(str, maxLen) {
716
+ if (str.length <= maxLen) return str;
717
+ if (maxLen <= 3) return str.slice(0, maxLen);
718
+ return str.slice(0, maxLen - 1) + "…";
719
+ }
720
+ /**
721
+ * List environment variables on the current app.
722
+ */
723
+ async function listEnvVars(options) {
724
+ const isVerbose = Boolean(options.verbose);
725
+ const { creds, app } = loadClientContext();
726
+ const url = `${creds.gateway_url}/v1/apps/${encodeURIComponent(app)}/env`;
756
727
  if (isVerbose) console.log(`[wawesome:verbose] GET ${url}`);
757
728
  const res = await fetch(url, {
758
729
  method: "GET",
759
- headers: { Authorization: `Bearer ${tenantJwt}` }
730
+ headers: { Authorization: `Bearer ${creds.tenant_jwt}` }
760
731
  });
761
732
  if (!res.ok) {
762
733
  const errorBody = await res.text();
763
734
  if (res.status === 401) console.error("[wawesome] Error: Authentication expired. Run 'wawesome login' again.");
764
735
  else {
765
- console.error(`[wawesome] Error: Failed to list versions (HTTP ${res.status}).`);
736
+ console.error(`[wawesome] Error: Failed to list variables (HTTP ${res.status}).`);
766
737
  if (isVerbose) console.error(`[wawesome:verbose] Response: ${errorBody}`);
767
738
  }
768
739
  process.exit(1);
769
740
  }
770
- return await res.json();
741
+ const data = await res.json();
742
+ if (!data.variables || data.variables.length === 0) {
743
+ console.log(`[wawesome] No environment variables set for app '${app}'.`);
744
+ return;
745
+ }
746
+ const availableWidth = (process.stdout.columns && process.stdout.columns > 40 ? process.stdout.columns : 80) - 12;
747
+ let rawMaxKeyLen = 15;
748
+ let rawMaxValLen = 15;
749
+ for (const item of data.variables) {
750
+ if (item.key.length > rawMaxKeyLen) rawMaxKeyLen = item.key.length;
751
+ if (item.value.length > rawMaxValLen) rawMaxValLen = item.value.length;
752
+ }
753
+ const maxKeyLen = Math.min(rawMaxKeyLen, Math.max(15, Math.floor(availableWidth * .4)));
754
+ const maxValLen = Math.min(rawMaxValLen, Math.max(15, availableWidth - maxKeyLen));
755
+ console.log(`\n📋 \x1b[1mEnvironment variables for '${app}'\x1b[0m\n`);
756
+ const headerKey = "KEY".padEnd(maxKeyLen);
757
+ const headerVal = "VALUE".padEnd(maxValLen);
758
+ console.log(`${headerKey} | ${headerVal} | SECRET`);
759
+ console.log(`${"-".repeat(maxKeyLen)}-|- ${"-".repeat(maxValLen)} |-------`);
760
+ for (const item of data.variables) {
761
+ const truncatedKey = truncate(item.key, maxKeyLen);
762
+ const truncatedVal = truncate(item.value, maxValLen);
763
+ const keyStr = truncatedKey.padEnd(maxKeyLen);
764
+ const valStr = truncatedVal.padEnd(maxValLen);
765
+ const secretStr = item.is_secret ? "\x1B[33mtrue\x1B[0m" : "false";
766
+ console.log(`${keyStr} | ${valStr} | ${secretStr}`);
767
+ }
768
+ console.log("");
771
769
  }
772
770
  /**
773
- * List existing function versions.
771
+ * Delete an environment variable on the current app.
774
772
  */
775
- async function listVersions(options) {
773
+ async function removeEnvVar(key, options) {
776
774
  const isVerbose = Boolean(options.verbose);
777
- const env = options.env || "production";
778
- const creds = readCredentials();
779
- if (!creds) {
780
- console.error("[wawesome] Error: Not logged in. Run 'wawesome login' first.");
781
- process.exit(1);
782
- }
783
- const config = readFunctionConfig();
784
- if (!config) {
785
- console.error("[wawesome] Error: No wawesome-function.json found in the current directory.");
775
+ if (!key) {
776
+ console.error("[wawesome] Error: Missing variable key. Usage: wawesome env rm <KEY>");
786
777
  process.exit(1);
787
778
  }
788
- const { app, function: funcName } = config;
789
- const data = await fetchVersions(creds.gateway_url, creds.tenant_jwt, app, funcName, env, isVerbose);
790
- if (!data.versions || data.versions.length === 0) {
791
- console.log(`[wawesome] No versions found for '${app}/${funcName}'. Deploy code first using 'wawesome deploy'.`);
792
- return;
779
+ const { creds, app } = loadClientContext();
780
+ const url = `${creds.gateway_url}/v1/apps/${encodeURIComponent(app)}/env/${encodeURIComponent(key)}`;
781
+ if (isVerbose) console.log(`[wawesome:verbose] DELETE ${url}`);
782
+ const res = await fetch(url, {
783
+ method: "DELETE",
784
+ headers: { Authorization: `Bearer ${creds.tenant_jwt}` }
785
+ });
786
+ if (!res.ok) {
787
+ const errorBody = await res.text();
788
+ if (res.status === 401) console.error("[wawesome] Error: Authentication expired. Run 'wawesome login' again.");
789
+ else if (res.status === 404) console.error(`[wawesome] Error: Variable '${key}' not found on app '${app}'.`);
790
+ else {
791
+ console.error(`[wawesome] Error: Failed to delete variable '${key}' (HTTP ${res.status}).`);
792
+ if (isVerbose) console.error(`[wawesome:verbose] Response: ${errorBody}`);
793
+ }
794
+ process.exit(1);
795
+ }
796
+ console.log(`[wawesome] ✅ Deleted variable '${key}' from app '${app}'.`);
797
+ }
798
+ /**
799
+ * Dispatcher function for `wawesome env` CLI command.
800
+ */
801
+ async function envCommand(action, key, value, options) {
802
+ if (!action || action === "list" || action === "ls") return listEnvVars(options);
803
+ if (action === "set") return setEnvVar(key, value, options);
804
+ if (action === "rm" || action === "remove" || action === "delete" || action === "unset") return removeEnvVar(key, options);
805
+ console.error(`[wawesome] Error: Unknown env action '${action}'. Available actions: list, set, rm.`);
806
+ process.exit(1);
807
+ }
808
+ //#endregion
809
+ //#region src/provision.ts
810
+ /** The gateway's own words for a failure, or a plain HTTP status if it gave none. */
811
+ async function rejected(res, fallback) {
812
+ if (res.status === 401) return new GatewayError("Authentication expired. Run 'wawesome login' again.", 401);
813
+ return asGatewayError(res, `${fallback} (HTTP ${res.status}).`);
814
+ }
815
+ function authHeaders(creds) {
816
+ return {
817
+ Authorization: `Bearer ${creds.tenant_jwt}`,
818
+ "Content-Type": "application/json"
819
+ };
820
+ }
821
+ /**
822
+ * Make sure the App exists before anything is attached to it.
823
+ *
824
+ * Environment variables and subscriptions are both App-scoped, and neither
825
+ * endpoint creates one — deploy would, but it runs last, and a Function that
826
+ * goes live before its secrets do is a Function that fails its first request.
827
+ *
828
+ * Listing first rather than creating and reading the error keeps the common
829
+ * case ("I already have this App") off the failure path; an App that appears in
830
+ * between is still treated as the success it is.
831
+ */
832
+ async function ensureApp(creds, appSlug) {
833
+ const listRes = await fetch(`${creds.gateway_url}/v1/apps`, { headers: { Authorization: `Bearer ${creds.tenant_jwt}` } });
834
+ if (!listRes.ok) throw await rejected(listRes, "Could not list the Tenant's apps");
835
+ if ((await listRes.json()).applications?.some((app) => app.slug === appSlug)) return;
836
+ const createRes = await fetch(`${creds.gateway_url}/v1/apps`, {
837
+ method: "POST",
838
+ headers: authHeaders(creds),
839
+ body: JSON.stringify({
840
+ name: appSlug,
841
+ slug: appSlug
842
+ })
843
+ });
844
+ if (createRes.ok) return;
845
+ const error = await rejected(createRes, `Could not create the app '${appSlug}'`);
846
+ if (/already exists/i.test(error.message)) return;
847
+ throw error;
848
+ }
849
+ /**
850
+ * Enable one catalogue provider for the App.
851
+ *
852
+ * A template declares the providers it calls; without the subscription the
853
+ * platform's egress policy denies those calls, so this is what stands between a
854
+ * scaffolded template and an outbound request that silently fails at runtime.
855
+ */
856
+ async function enableEgressProvider(creds, appSlug, providerKey) {
857
+ const url = `${creds.gateway_url}/v1/apps/${encodeURIComponent(appSlug)}/egress/subscriptions`;
858
+ const res = await fetch(url, {
859
+ method: "POST",
860
+ headers: authHeaders(creds),
861
+ body: JSON.stringify({ provider_key: providerKey })
862
+ });
863
+ if (!res.ok) throw await rejected(res, `Could not enable outbound provider '${providerKey}'`);
864
+ }
865
+ //#endregion
866
+ //#region src/scaffold.ts
867
+ const MANIFEST_FILE = "template.json";
868
+ const PACKAGE_FILE = "package.json";
869
+ const FUNCTION_CONFIG_FILE = "wawesome-function.json";
870
+ /** Read the template's requirements declaration out of a scaffolded directory. */
871
+ function readTemplateManifest(dir) {
872
+ const manifestPath = path.join(dir, MANIFEST_FILE);
873
+ if (!fs.existsSync(manifestPath)) throw new Error(`The template has no ${MANIFEST_FILE}, so there is nothing to set it up from.`);
874
+ let raw;
875
+ try {
876
+ raw = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
877
+ } catch (err) {
878
+ throw new Error(`The template's ${MANIFEST_FILE} is not valid JSON: ${errorText(err)}`);
879
+ }
880
+ return {
881
+ env: Array.isArray(raw.env) ? raw.env : [],
882
+ providers: Array.isArray(raw.providers) ? raw.providers : [],
883
+ post_deploy: typeof raw.post_deploy === "string" ? raw.post_deploy : ""
884
+ };
885
+ }
886
+ /**
887
+ * Patch the two configuration files, and nothing else.
888
+ *
889
+ * Every placeholder originally scoped for substitution turned out to be
890
+ * something else: the Tenant slug never appears in template source, and a
891
+ * template's environment-variable *names* are fixed by its own code. What is
892
+ * left is identity — which App this is, and what the Function is called.
893
+ */
894
+ function applyTemplateIdentity(dir, identity) {
895
+ patchJson(path.join(dir, PACKAGE_FILE), (pkg) => ({
896
+ ...pkg,
897
+ name: identity.functionName
898
+ }));
899
+ patchJson(path.join(dir, FUNCTION_CONFIG_FILE), (config) => ({
900
+ ...config,
901
+ app: identity.app,
902
+ function: identity.functionName
903
+ }));
904
+ }
905
+ function patchJson(file, patch) {
906
+ if (!fs.existsSync(file)) throw new Error(`The template is missing ${path.basename(file)}, which scaffolding must patch.`);
907
+ let current;
908
+ try {
909
+ current = JSON.parse(fs.readFileSync(file, "utf-8"));
910
+ } catch (err) {
911
+ throw new Error(`The template's ${path.basename(file)} is not valid JSON: ${errorText(err)}`);
912
+ }
913
+ fs.writeFileSync(file, JSON.stringify(patch(current), null, 2) + "\n", "utf-8");
914
+ }
915
+ /**
916
+ * Which of the files a scaffold is about to write are already there.
917
+ *
918
+ * Checked before the first byte is written: half a template over half a project
919
+ * is worse than refusing, and the user is the only one who knows which they
920
+ * meant to keep.
921
+ */
922
+ function collidingPaths(dir, relativePaths) {
923
+ return relativePaths.filter((relative) => fs.existsSync(path.join(dir, relative)));
924
+ }
925
+ /**
926
+ * Fill the post-deploy message in. `{{url}}` is the only placeholder anywhere in
927
+ * the template system, and it never touches a source file — if the address could
928
+ * not be resolved the message still prints, with the placeholder left visible
929
+ * rather than a confident "undefined".
930
+ */
931
+ function renderPostDeploy(postDeploy, invokeUrl) {
932
+ if (!invokeUrl) return postDeploy;
933
+ return postDeploy.split("{{url}}").join(invokeUrl);
934
+ }
935
+ /**
936
+ * Normalise arbitrary input into a legal DNS label, returning an empty string
937
+ * when nothing legal survives — callers decide whether that is an error.
938
+ */
939
+ function sanitizeSlug(raw) {
940
+ let label = "";
941
+ for (const c of raw.trim().toLowerCase()) if (c >= "a" && c <= "z") label += c;
942
+ else if (c >= "0" && c <= "9") label += c;
943
+ else if (label.length > 0 && !label.endsWith("-")) label += "-";
944
+ label = label.slice(0, 63);
945
+ while (label.endsWith("-")) label = label.slice(0, -1);
946
+ return label;
947
+ }
948
+ /**
949
+ * Whether `candidate` is already a legal DNS label — i.e. whether
950
+ * {@link sanitizeSlug} would leave it untouched.
951
+ */
952
+ function isLegalSlug(candidate) {
953
+ return candidate.length > 0 && candidate.length <= 63 && !candidate.startsWith("-") && !candidate.endsWith("-") && !candidate.includes("--") && /^[a-z0-9-]+$/.test(candidate);
954
+ }
955
+ //#endregion
956
+ //#region src/tarball.ts
957
+ /**
958
+ * Reading a repository archive, so scaffolding needs no git.
959
+ *
960
+ * Git being absent is the common case for the audience this platform is for, and
961
+ * on Windows it is the *normal* case — so the template arrives as a `.tar.gz`
962
+ * over plain HTTP and is unpacked here. Node ships gzip; the tar half is 512-byte
963
+ * blocks, which is little enough code that carrying a dependency for it would
964
+ * cost more than it saves.
965
+ *
966
+ * An archive is untrusted input even when it comes from a URL the platform
967
+ * chose: extraction refuses anything whose path could land outside the
968
+ * destination, and refuses links entirely, before writing a single file.
969
+ */
970
+ const BLOCK_SIZE = 512;
971
+ /** Where each field a header carries begins, and how long it is. */
972
+ const NAME = {
973
+ at: 0,
974
+ len: 100
975
+ };
976
+ const MODE = {
977
+ at: 100,
978
+ len: 8
979
+ };
980
+ const SIZE = {
981
+ at: 124,
982
+ len: 12
983
+ };
984
+ const TYPE_FLAG = 156;
985
+ const MAGIC = {
986
+ at: 257,
987
+ len: 6
988
+ };
989
+ const PREFIX = {
990
+ at: 345,
991
+ len: 155
992
+ };
993
+ /** Entry types extraction acts on. Everything else is metadata or refused. */
994
+ const TYPE_FILE = "0";
995
+ const TYPE_FILE_ALT = "\0";
996
+ const TYPE_DIRECTORY = "5";
997
+ const TYPE_SYMLINK = "2";
998
+ const TYPE_HARDLINK = "1";
999
+ const TYPE_PAX_NEXT = "x";
1000
+ const TYPE_PAX_GLOBAL = "g";
1001
+ const TYPE_GNU_LONGNAME = "L";
1002
+ /** A tar the CLI cannot make sense of, phrased for whoever is watching. */
1003
+ var ArchiveError = class extends Error {};
1004
+ function field(block, at, len) {
1005
+ const raw = block.toString("utf-8", at, at + len);
1006
+ const end = raw.indexOf("\0");
1007
+ return end === -1 ? raw : raw.slice(0, end);
1008
+ }
1009
+ function octal(block, at, len) {
1010
+ const text = field(block, at, len).trim();
1011
+ if (!text) return 0;
1012
+ const value = parseInt(text, 8);
1013
+ return Number.isFinite(value) ? value : 0;
1014
+ }
1015
+ /**
1016
+ * The path an entry claims, honouring the two ways a long one is recorded:
1017
+ * split across the `ustar` prefix field, or carried by the pax header that
1018
+ * precedes it. Both come out of a real `git archive` — which one you get depends
1019
+ * only on where the path's slashes happen to fall.
1020
+ */
1021
+ function entryPath(block, paxPath) {
1022
+ if (paxPath) return paxPath;
1023
+ const name = field(block, NAME.at, NAME.len);
1024
+ const prefix = field(block, PREFIX.at, PREFIX.len);
1025
+ return prefix ? `${prefix}/${name}` : name;
1026
+ }
1027
+ /** The `path=` record of a pax extended header, if it declares one. */
1028
+ function paxHeaderPath(body) {
1029
+ let offset = 0;
1030
+ while (offset < body.length) {
1031
+ const space = body.indexOf(32, offset);
1032
+ if (space === -1) break;
1033
+ const length = parseInt(body.toString("ascii", offset, space), 10);
1034
+ if (!Number.isFinite(length) || length <= 0) break;
1035
+ const record = body.toString("utf-8", space + 1, offset + length).replace(/\n$/, "");
1036
+ const eq = record.indexOf("=");
1037
+ if (eq !== -1 && record.slice(0, eq) === "path") return record.slice(eq + 1);
1038
+ offset += length;
1039
+ }
1040
+ return null;
1041
+ }
1042
+ /**
1043
+ * Every file in a tar, in archive order.
1044
+ *
1045
+ * Refuses links rather than skipping them: a symlink extracted into the
1046
+ * destination turns a later, innocent-looking entry into a write anywhere on
1047
+ * the filesystem, and no template has a reason to ship one.
1048
+ */
1049
+ function readEntries(tar) {
1050
+ const entries = [];
1051
+ let paxPath = null;
1052
+ let offset = 0;
1053
+ let sawHeader = false;
1054
+ while (offset + BLOCK_SIZE <= tar.length) {
1055
+ const block = tar.subarray(offset, offset + BLOCK_SIZE);
1056
+ offset += BLOCK_SIZE;
1057
+ if (block.every((byte) => byte === 0)) break;
1058
+ if (!field(block, MAGIC.at, MAGIC.len).startsWith("ustar")) throw new ArchiveError("The downloaded file is not a tar archive.");
1059
+ sawHeader = true;
1060
+ const size = octal(block, SIZE.at, SIZE.len);
1061
+ const bodyEnd = offset + size;
1062
+ if (bodyEnd > tar.length) throw new ArchiveError("The downloaded archive is truncated.");
1063
+ const body = tar.subarray(offset, bodyEnd);
1064
+ offset += Math.ceil(size / BLOCK_SIZE) * BLOCK_SIZE;
1065
+ const type = String.fromCharCode(block[TYPE_FLAG]);
1066
+ if (type === TYPE_PAX_NEXT || type === TYPE_GNU_LONGNAME) {
1067
+ paxPath = type === TYPE_GNU_LONGNAME ? field(body, 0, body.length) : paxHeaderPath(body);
1068
+ continue;
1069
+ }
1070
+ if (type === TYPE_PAX_GLOBAL) continue;
1071
+ const recorded = entryPath(block, paxPath);
1072
+ paxPath = null;
1073
+ if (type === TYPE_SYMLINK || type === TYPE_HARDLINK) throw new ArchiveError(`The archive contains a link ('${recorded}'), which is not extracted.`);
1074
+ if (type === TYPE_DIRECTORY) continue;
1075
+ if (type !== TYPE_FILE && type !== TYPE_FILE_ALT) continue;
1076
+ entries.push({
1077
+ path: recorded,
1078
+ mode: octal(block, MODE.at, MODE.len),
1079
+ body
1080
+ });
1081
+ }
1082
+ if (!sawHeader) throw new ArchiveError("The downloaded file is not a tar archive.");
1083
+ return entries;
1084
+ }
1085
+ /** Drop the archive's single root directory, the way `--strip-components=1` does. */
1086
+ function withoutArchiveRoot(entryPath) {
1087
+ const firstSlash = entryPath.indexOf("/");
1088
+ if (firstSlash === -1) return null;
1089
+ return entryPath.slice(firstSlash + 1);
1090
+ }
1091
+ /**
1092
+ * The path an entry takes inside the template directory, or `null` if it belongs
1093
+ * to a different one. `.` means the template owns the whole repository.
1094
+ */
1095
+ function withinDirectory(entryPath, directory) {
1096
+ if (directory === "." || directory === "") return entryPath;
1097
+ const prefix = `${directory}/`;
1098
+ return entryPath.startsWith(prefix) ? entryPath.slice(prefix.length) : null;
1099
+ }
1100
+ /**
1101
+ * Unpack one template directory out of a repository archive.
1102
+ *
1103
+ * Contents are written exactly as they were recorded — a template is a real
1104
+ * project, so nothing here rewrites, re-encodes or substitutes anything. The
1105
+ * whole archive is validated before the first write, so a refused entry leaves
1106
+ * the destination as it found it rather than half-scaffolded.
1107
+ *
1108
+ * Returns the paths written, relative to `destination`.
1109
+ */
1110
+ function extractTemplateDirectory(archive, options) {
1111
+ let tar;
1112
+ try {
1113
+ tar = zlib.gunzipSync(archive);
1114
+ } catch {
1115
+ throw new ArchiveError("The downloaded file is not a gzip archive.");
1116
+ }
1117
+ const { directory, destination } = options;
1118
+ const root = path.resolve(destination);
1119
+ const planned = [];
1120
+ for (const entry of readEntries(tar)) {
1121
+ if (path.posix.isAbsolute(entry.path) || /^[A-Za-z]:/.test(entry.path)) throw new ArchiveError(`The archive contains an absolute path ('${entry.path}').`);
1122
+ const stripped = withoutArchiveRoot(entry.path);
1123
+ if (stripped === null) continue;
1124
+ const relative = withinDirectory(stripped, directory);
1125
+ if (relative === null || relative === "") continue;
1126
+ const absolute = path.resolve(root, relative);
1127
+ if (absolute !== root && !absolute.startsWith(root + path.sep)) throw new ArchiveError(`The archive contains a path outside the project ('${entry.path}').`);
1128
+ planned.push({
1129
+ absolute,
1130
+ relative,
1131
+ entry
1132
+ });
1133
+ }
1134
+ if (planned.length === 0) throw new ArchiveError(`The archive contains no directory named '${directory}'.`);
1135
+ for (const { absolute, entry } of planned) {
1136
+ fs.mkdirSync(path.dirname(absolute), { recursive: true });
1137
+ fs.writeFileSync(absolute, entry.body, { mode: entry.mode & 511 || 420 });
1138
+ }
1139
+ return planned.map(({ relative }) => relative);
1140
+ }
1141
+ //#endregion
1142
+ //#region src/templates.ts
1143
+ /**
1144
+ * Read the template catalogue.
1145
+ *
1146
+ * Deliberately unauthenticated: discovery has to work for someone who has not
1147
+ * signed up yet, so no credential is read and none is sent — a stale token file
1148
+ * left over from a previous install cannot turn this into a rejection.
1149
+ */
1150
+ async function fetchTemplateCatalog(gatewayUrl) {
1151
+ let res;
1152
+ try {
1153
+ res = await fetch(`${gatewayUrl}/v1/templates`);
1154
+ } catch (err) {
1155
+ throw new Error(`Could not reach ${gatewayUrl} to list templates. ${err instanceof Error ? err.message : err}`);
1156
+ }
1157
+ if (!res.ok) throw new Error(`${gatewayUrl} could not list templates (HTTP ${res.status}).`);
1158
+ let data;
1159
+ try {
1160
+ data = await res.json();
1161
+ } catch {
1162
+ throw new Error(`${gatewayUrl} answered with something that is not a template list.`);
1163
+ }
1164
+ if (!Array.isArray(data.templates)) throw new Error(`${gatewayUrl} answered with something that is not a template list.`);
1165
+ return data.templates;
1166
+ }
1167
+ /**
1168
+ * Find one template by the name a user typed after `--template`.
1169
+ *
1170
+ * Resolved against the catalogue rather than a list compiled in here, so a
1171
+ * template added yesterday is scaffoldable by a CLI released last year. An
1172
+ * unknown name answers with the names that do exist: the mistake is almost
1173
+ * always a typo, and the fix is on screen.
1174
+ */
1175
+ async function resolveTemplate(gatewayUrl, name) {
1176
+ const templates = await fetchTemplateCatalog(gatewayUrl);
1177
+ const match = templates.find((template) => template.name === name);
1178
+ if (match) return match;
1179
+ if (templates.length === 0) throw new Error(`No templates are available from ${gatewayUrl} yet.`);
1180
+ const available = templates.map((template) => template.name).join(", ");
1181
+ throw new Error(`No template called '${name}'. Available templates: ${available}.`);
1182
+ }
1183
+ /**
1184
+ * Download a template's archive.
1185
+ *
1186
+ * From the archive host the catalogue named, rather than the REST API's tarball
1187
+ * endpoint: that one is rate-limited per IP for unauthenticated callers, so
1188
+ * behind corporate NAT or on a shared runner the very first thing a new user
1189
+ * does would fail intermittently, for a reason they cannot diagnose.
1190
+ */
1191
+ async function downloadTemplateArchive(archiveUrl) {
1192
+ let res;
1193
+ try {
1194
+ res = await fetch(archiveUrl);
1195
+ } catch (err) {
1196
+ throw new Error(`Could not download the template from ${archiveUrl}. ${errorText(err)}`);
1197
+ }
1198
+ if (!res.ok) throw new Error(`Could not download the template from ${archiveUrl} (HTTP ${res.status}). The template's stable ref may not have been published yet.`);
1199
+ return Buffer.from(await res.arrayBuffer());
1200
+ }
1201
+ /** List every template in the catalogue. */
1202
+ async function listTemplates(options) {
1203
+ const gatewayUrl = getGatewayUrl(options.api);
1204
+ if (options.verbose) console.log(`[wawesome:verbose] GET ${gatewayUrl}/v1/templates`);
1205
+ let templates;
1206
+ try {
1207
+ templates = await fetchTemplateCatalog(gatewayUrl);
1208
+ } catch (err) {
1209
+ console.error(`[wawesome] Error: ${err instanceof Error ? err.message : err}`);
1210
+ process.exit(1);
1211
+ return;
1212
+ }
1213
+ if (templates.length === 0) {
1214
+ console.log("[wawesome] No templates available yet.");
1215
+ return;
1216
+ }
1217
+ console.log("\n📦 \x1B[1mTemplates\x1B[0m\n");
1218
+ for (const template of templates) {
1219
+ console.log(` \x1b[36m${template.name}\x1b[0m — ${template.title}`);
1220
+ console.log(` ${template.description}`);
1221
+ if (template.tags.length > 0) console.log(` \x1b[90m${template.tags.join(", ")}\x1b[0m`);
1222
+ console.log(` \x1b[90m${template.source_url}\x1b[0m`);
1223
+ if (options.verbose) console.log(` \x1b[90mref ${template.ref} · ${template.archive_url}\x1b[0m`);
1224
+ console.log("");
1225
+ }
1226
+ }
1227
+ /** Dispatch for `wawesome templates [action]`. */
1228
+ async function templatesCommand(action, options) {
1229
+ if (!action || action === "list" || action === "ls") return listTemplates(options);
1230
+ console.error(`[wawesome] Error: Unknown templates action '${action}'. Available actions: list (alias: ls).`);
1231
+ process.exit(1);
1232
+ }
1233
+ //#endregion
1234
+ //#region src/init.ts
1235
+ /** Bound on the re-prompt loop, so unusable input exits instead of looping. */
1236
+ const MAX_SLUG_ATTEMPTS = 5;
1237
+ /**
1238
+ * Ask for a name that becomes part of the public URL, until the answer is one.
1239
+ *
1240
+ * Both names this asks for — the App the Function belongs to, and the Function
1241
+ * itself — end up in the address a client reads, so neither may be taken as
1242
+ * typed. An illegal answer is re-offered as a suggestion rather than rewritten:
1243
+ * the user sees the name they will get before agreeing to it.
1244
+ */
1245
+ async function promptForSlug(session, label, proposed) {
1246
+ let suggestion = sanitizeSlug(proposed);
1247
+ for (let attempt = 0; attempt < MAX_SLUG_ATTEMPTS; attempt++) {
1248
+ const answer = await session.ask(` ${label}?`, suggestion);
1249
+ if (isLegalSlug(answer)) return answer;
1250
+ const sanitized = sanitizeSlug(answer);
1251
+ if (sanitized) {
1252
+ console.log(`[wawesome] '${answer}' can't be used as ${anArticle(label)}. Suggested: '${sanitized}'.`);
1253
+ suggestion = sanitized;
1254
+ } else console.log(`[wawesome] ${anArticle(label, true)} needs lowercase letters or numbers, separated by single hyphens.`);
1255
+ }
1256
+ console.error(`[wawesome] Error: no usable ${label} after ${MAX_SLUG_ATTEMPTS} attempts. Nothing was written.`);
1257
+ console.error(`[wawesome] Run 'wawesome init' again once you know what to call it.`);
1258
+ process.exit(1);
1259
+ }
1260
+ /** "an App slug" / "A Function name" — so one prompt reads for both names. */
1261
+ function anArticle(label, capitalized = false) {
1262
+ const article = /^[aeiou]/i.test(label) ? "an" : "a";
1263
+ return `${capitalized ? article[0].toUpperCase() + article.slice(1) : article} ${label}`;
1264
+ }
1265
+ /** Report a failure the user can act on, and stop. */
1266
+ function fail(message, ...advice) {
1267
+ console.error(`[wawesome] Error: ${message}`);
1268
+ for (const line of advice) console.error(`[wawesome] ${line}`);
1269
+ process.exit(1);
1270
+ throw new Error(message);
1271
+ }
1272
+ /**
1273
+ * Ask for every variable the template declared.
1274
+ *
1275
+ * The pointer to where the value lives is shown with the question, because the
1276
+ * user is being asked for a value that exists in somebody else's dashboard and
1277
+ * hunting for it in third-party documentation is where a first deploy stalls.
1278
+ * A blank answer is allowed even for a required variable: for a webhook secret
1279
+ * the value does not exist yet — the endpoint has to be created first — so
1280
+ * refusing to continue would be refusing the only order that works.
1281
+ */
1282
+ async function promptForDeclaredEnv(session, declared) {
1283
+ if (declared.length === 0) return [];
1284
+ console.log("\n[wawesome] This template needs a few values before it can run.\n");
1285
+ const answers = [];
1286
+ for (const variable of declared) {
1287
+ const flags = [variable.required ? "required" : "optional"];
1288
+ if (variable.secret) flags.push("stored write-only");
1289
+ console.log(` \x1b[1m${variable.key}\x1b[0m \x1b[90m(${flags.join(", ")})\x1b[0m`);
1290
+ console.log(` ${variable.description}`);
1291
+ console.log(` \x1b[90mWhere to find it: ${variable.where_to_find}\x1b[0m`);
1292
+ const value = await session.ask(` ${variable.key}?`, "");
1293
+ console.log("");
1294
+ answers.push({
1295
+ declared: variable,
1296
+ value
1297
+ });
1298
+ }
1299
+ return answers;
1300
+ }
1301
+ /**
1302
+ * Satisfy the template's declarations against the platform.
1303
+ *
1304
+ * The manifest declares; nothing here is template-specific. Each declaration
1305
+ * goes through an endpoint the platform already ships, which is what keeps a new
1306
+ * template from needing a CLI release.
1307
+ */
1308
+ async function wireUp(creds, appSlug, manifest, answers) {
1309
+ const scaffolded = "Your project is scaffolded — fix this, then run 'wawesome deploy'.";
1310
+ try {
1311
+ await ensureApp(creds, appSlug);
1312
+ } catch (err) {
1313
+ fail(errorText(err), scaffolded);
1314
+ }
1315
+ for (const { declared, value } of answers) {
1316
+ if (!value) {
1317
+ const secretFlag = declared.secret ? " --secret" : "";
1318
+ console.log(`[wawesome] ${declared.key} left blank. Set it with: wawesome env set ${declared.key} <value>${secretFlag}`);
1319
+ continue;
1320
+ }
1321
+ try {
1322
+ await putEnvVar(creds, appSlug, declared.key, value, declared.secret);
1323
+ } catch (err) {
1324
+ fail(errorText(err), scaffolded);
1325
+ }
1326
+ console.log(`[wawesome] ✅ Stored ${declared.key}${declared.secret ? " (secret)" : ""}.`);
1327
+ }
1328
+ for (const provider of manifest.providers) {
1329
+ try {
1330
+ await enableEgressProvider(creds, appSlug, provider);
1331
+ } catch (err) {
1332
+ fail(errorText(err), scaffolded);
1333
+ }
1334
+ console.log(`[wawesome] ✅ Enabled outbound calls to '${provider}'.`);
1335
+ }
1336
+ }
1337
+ /**
1338
+ * Scaffold from a catalogue template, wire up what it declared, and deploy it.
1339
+ *
1340
+ * The template arrives as a repository archive over plain HTTP — no git, which
1341
+ * makes this work on a machine that has never had it installed, and on Windows.
1342
+ * It is unpacked into a staging directory first, so a template that turns out to
1343
+ * collide with what is already here leaves the directory exactly as it found it.
1344
+ */
1345
+ async function initFromTemplate(templateName, options) {
1346
+ const isVerbose = Boolean(options.verbose);
1347
+ const gatewayUrl = getGatewayUrl(options.api);
1348
+ const cwd = process.cwd();
1349
+ const dirName = path.basename(cwd);
1350
+ let template;
1351
+ try {
1352
+ template = await resolveTemplate(gatewayUrl, templateName);
1353
+ } catch (err) {
1354
+ fail(errorText(err));
1355
+ }
1356
+ console.log(`[wawesome] Fetching ${template.title} (${template.ref})...`);
1357
+ if (isVerbose) console.log(`[wawesome:verbose] GET ${template.archive_url}`);
1358
+ let archive;
1359
+ try {
1360
+ archive = await downloadTemplateArchive(template.archive_url);
1361
+ } catch (err) {
1362
+ fail(errorText(err));
1363
+ }
1364
+ const staging = fs.mkdtempSync(path.join(os.tmpdir(), "wawesome-template-"));
1365
+ const sweepStaging = () => fs.rmSync(staging, {
1366
+ recursive: true,
1367
+ force: true
1368
+ });
1369
+ process.once("exit", sweepStaging);
1370
+ const session = openPromptSession();
1371
+ let functionName;
1372
+ let appSlug;
1373
+ let manifest;
1374
+ try {
1375
+ let files;
1376
+ try {
1377
+ files = extractTemplateDirectory(archive, {
1378
+ directory: template.directory,
1379
+ destination: staging
1380
+ });
1381
+ manifest = readTemplateManifest(staging);
1382
+ } catch (err) {
1383
+ fail(errorText(err));
1384
+ }
1385
+ const collisions = collidingPaths(cwd, files);
1386
+ if (collisions.length > 0) fail(`${collisions.join(", ")} already exist${collisions.length === 1 ? "s" : ""} here.`, "Run this in an empty directory, or move those files aside first. Nothing was written.");
1387
+ functionName = await promptForSlug(session, "Function name", readFunctionConfig(staging)?.function || dirName);
1388
+ console.log(" (an App groups the Functions of one project — its slug is part of the public URL)");
1389
+ appSlug = await promptForSlug(session, "App slug", dirName);
1390
+ try {
1391
+ fs.cpSync(staging, cwd, { recursive: true });
1392
+ applyTemplateIdentity(cwd, {
1393
+ app: appSlug,
1394
+ functionName
1395
+ });
1396
+ } catch (err) {
1397
+ fail(errorText(err), `Some of '${template.name}' may have been written to ${cwd}.`);
1398
+ }
1399
+ console.log(`\n[wawesome] ✅ Scaffolded ${files.length} files from '${template.name}'.`);
1400
+ } finally {
1401
+ sweepStaging();
1402
+ process.off("exit", sweepStaging);
1403
+ }
1404
+ let answers = [];
1405
+ let creds;
1406
+ try {
1407
+ creds = readCredentials();
1408
+ if (creds) answers = await promptForDeclaredEnv(session, manifest.env);
1409
+ } finally {
1410
+ session.close();
1411
+ }
1412
+ if (!creds) {
1413
+ console.log("\n[wawesome] 🎉 Project ready. Next steps:");
1414
+ console.log(" 1. npm install");
1415
+ console.log(" 2. wawesome login");
1416
+ console.log(" 3. wawesome deploy\n");
1417
+ return;
1418
+ }
1419
+ await wireUp(creds, appSlug, manifest, answers);
1420
+ const result = await deploy(void 0, {
1421
+ out: "dist/index.js",
1422
+ verbose: options.verbose
1423
+ });
1424
+ if (manifest.post_deploy) {
1425
+ console.log(renderPostDeploy(manifest.post_deploy, result.invokeUrl));
1426
+ console.log("");
1427
+ }
1428
+ }
1429
+ /**
1430
+ * Scaffold a new wawesome function project in the current directory.
1431
+ */
1432
+ async function init(options) {
1433
+ if (options.template) return initFromTemplate(options.template, options);
1434
+ const isVerbose = Boolean(options.verbose);
1435
+ const cwd = process.cwd();
1436
+ const dirName = path.basename(cwd);
1437
+ console.log("[wawesome] Initializing a new function project...\n");
1438
+ const session = openPromptSession();
1439
+ let functionName;
1440
+ let appSlug;
1441
+ try {
1442
+ functionName = await promptForSlug(session, "Function name", dirName);
1443
+ console.log(" (an App groups the Functions of one project — its slug is part of the public URL)");
1444
+ appSlug = await promptForSlug(session, "App slug", dirName);
1445
+ } finally {
1446
+ session.close();
1447
+ }
1448
+ const entry = "src/index.ts";
1449
+ if (isVerbose) console.log(`[wawesome:verbose] function=${functionName}, app=${appSlug}, entry=${entry}`);
1450
+ const configContent = {
1451
+ app: appSlug,
1452
+ function: functionName,
1453
+ entry
1454
+ };
1455
+ const configPath = path.join(cwd, "wawesome-function.json");
1456
+ if (fs.existsSync(configPath)) console.log("[wawesome] wawesome-function.json already exists, skipping.");
1457
+ else {
1458
+ fs.writeFileSync(configPath, JSON.stringify(configContent, null, 2) + "\n", "utf-8");
1459
+ console.log("[wawesome] ✅ Created wawesome-function.json");
1460
+ }
1461
+ const srcDir = path.join(cwd, "src");
1462
+ const indexPath = path.join(srcDir, "index.ts");
1463
+ if (fs.existsSync(indexPath)) console.log("[wawesome] src/index.ts already exists, skipping.");
1464
+ else {
1465
+ fs.mkdirSync(srcDir, { recursive: true });
1466
+ fs.writeFileSync(indexPath, `/**
1467
+ * Serverless Function Handler
1468
+ * Standard HTTP fetch request handler
1469
+ */
1470
+ export default {
1471
+ async fetch(request: Request): Promise<Response> {
1472
+ return Response.json({
1473
+ message: "Hello, World!",
1474
+ });
1475
+ },
1476
+ };
1477
+ `, "utf-8");
1478
+ console.log("[wawesome] ✅ Created src/index.ts");
1479
+ }
1480
+ const pkgPath = path.join(cwd, "package.json");
1481
+ if (fs.existsSync(pkgPath)) console.log("[wawesome] package.json already exists, skipping.");
1482
+ else {
1483
+ const pkgContent = {
1484
+ name: functionName,
1485
+ type: "module",
1486
+ version: "1.0.0",
1487
+ description: `Serverless function: ${functionName}`,
1488
+ scripts: {
1489
+ build: "wawesome build",
1490
+ deploy: "wawesome deploy",
1491
+ typecheck: "tsc --noEmit"
1492
+ },
1493
+ devDependencies: {
1494
+ "wawesome": "^1.0.0",
1495
+ typescript: "^7.0.0"
1496
+ }
1497
+ };
1498
+ fs.writeFileSync(pkgPath, JSON.stringify(pkgContent, null, 2) + "\n", "utf-8");
1499
+ console.log("[wawesome] ✅ Created package.json");
1500
+ }
1501
+ const tsconfigPath = path.join(cwd, "tsconfig.json");
1502
+ if (fs.existsSync(tsconfigPath)) console.log("[wawesome] tsconfig.json already exists, skipping.");
1503
+ else {
1504
+ fs.writeFileSync(tsconfigPath, JSON.stringify({
1505
+ compilerOptions: {
1506
+ target: "ES2022",
1507
+ module: "ESNext",
1508
+ moduleResolution: "bundler",
1509
+ strict: true,
1510
+ noEmit: true,
1511
+ lib: [
1512
+ "ES2022",
1513
+ "DOM",
1514
+ "DOM.Iterable"
1515
+ ]
1516
+ },
1517
+ include: ["src"]
1518
+ }, null, 2) + "\n", "utf-8");
1519
+ console.log("[wawesome] ✅ Created tsconfig.json");
1520
+ }
1521
+ const gitignorePath = path.join(cwd, ".gitignore");
1522
+ if (fs.existsSync(gitignorePath)) console.log("[wawesome] .gitignore already exists, skipping.");
1523
+ else {
1524
+ fs.writeFileSync(gitignorePath, "node_modules\ndist\n", "utf-8");
1525
+ console.log("[wawesome] ✅ Created .gitignore");
1526
+ }
1527
+ console.log("\n[wawesome] 🎉 Project initialized! Next steps:");
1528
+ console.log(" 1. npm install");
1529
+ console.log(" 2. wawesome login");
1530
+ console.log(" 3. wawesome deploy\n");
1531
+ }
1532
+ //#endregion
1533
+ //#region src/version.ts
1534
+ async function fetchVersions(gatewayUrl, tenantJwt, app, funcName, env, isVerbose) {
1535
+ const url = `${gatewayUrl}/v1/apps/${encodeURIComponent(app)}/functions/${encodeURIComponent(funcName)}/versions?environment=${encodeURIComponent(env)}`;
1536
+ if (isVerbose) console.log(`[wawesome:verbose] GET ${url}`);
1537
+ const res = await fetch(url, {
1538
+ method: "GET",
1539
+ headers: { Authorization: `Bearer ${tenantJwt}` }
1540
+ });
1541
+ if (!res.ok) {
1542
+ const errorBody = await res.text();
1543
+ if (res.status === 401) console.error("[wawesome] Error: Authentication expired. Run 'wawesome login' again.");
1544
+ else {
1545
+ console.error(`[wawesome] Error: Failed to list versions (HTTP ${res.status}).`);
1546
+ if (isVerbose) console.error(`[wawesome:verbose] Response: ${errorBody}`);
1547
+ }
1548
+ process.exit(1);
1549
+ }
1550
+ return await res.json();
1551
+ }
1552
+ /**
1553
+ * List existing function versions.
1554
+ */
1555
+ async function listVersions(options) {
1556
+ const isVerbose = Boolean(options.verbose);
1557
+ const env = options.env || "production";
1558
+ const creds = readCredentials();
1559
+ if (!creds) {
1560
+ console.error("[wawesome] Error: Not logged in. Run 'wawesome login' first.");
1561
+ process.exit(1);
1562
+ }
1563
+ const config = readFunctionConfig();
1564
+ if (!config) {
1565
+ console.error("[wawesome] Error: No wawesome-function.json found in the current directory.");
1566
+ process.exit(1);
1567
+ }
1568
+ const { app, function: funcName } = config;
1569
+ const data = await fetchVersions(creds.gateway_url, creds.tenant_jwt, app, funcName, env, isVerbose);
1570
+ if (!data.versions || data.versions.length === 0) {
1571
+ console.log(`[wawesome] No versions found for '${app}/${funcName}'. Deploy code first using 'wawesome deploy'.`);
1572
+ return;
793
1573
  }
794
1574
  console.log(`\n📦 \x1b[1mVersions for '${app}/${funcName}' (environment: ${env})\x1b[0m\n`);
795
1575
  console.log("VERSION | HASH | CREATED AT | STATUS | ACTIVE");
@@ -894,177 +1674,6 @@ async function switchVersion(targetInput, options) {
894
1674
  console.log(`======================================================\n`);
895
1675
  }
896
1676
  //#endregion
897
- //#region src/env.ts
898
- const STANDARD_SECRET_MESSAGES = [
899
- "Encrypted at rest using AES-256",
900
- "This value can't be viewed again after you save it — only updated or deleted",
901
- "Only decrypted at the moment your function runs — never returned by the CLI, dashboard, or API after creation."
902
- ];
903
- /**
904
- * Load credentials and validate project config.
905
- */
906
- function loadClientContext() {
907
- const creds = readCredentials();
908
- if (!creds) {
909
- console.error("[wawesome] Error: Not logged in. Run 'wawesome login' first.");
910
- process.exit(1);
911
- }
912
- const config = readFunctionConfig();
913
- if (!config || !config.app || !config.app.trim()) {
914
- console.error("[wawesome] Error: No wawesome-function.json found in the current directory.");
915
- console.error("[wawesome] Run 'wawesome init' to create one, or create it manually.");
916
- process.exit(1);
917
- }
918
- return {
919
- creds,
920
- app: config.app.trim()
921
- };
922
- }
923
- /**
924
- * Set or overwrite an environment variable on the current app.
925
- */
926
- async function setEnvVar(key, value, options) {
927
- const isVerbose = Boolean(options.verbose);
928
- if (!key || value === void 0) {
929
- console.error("[wawesome] Error: Missing key or value. Usage: wawesome env set <KEY> <VALUE> [--secret]");
930
- process.exit(1);
931
- }
932
- const { creds, app } = loadClientContext();
933
- const isSecret = Boolean(options.secret);
934
- const url = `${creds.gateway_url}/v1/apps/${encodeURIComponent(app)}/env`;
935
- if (isVerbose) {
936
- console.log(`[wawesome:verbose] POST ${url}`);
937
- console.log(`[wawesome:verbose] Payload: key=${key}, is_secret=${isSecret}`);
938
- }
939
- const res = await fetch(url, {
940
- method: "POST",
941
- headers: {
942
- Authorization: `Bearer ${creds.tenant_jwt}`,
943
- "Content-Type": "application/json"
944
- },
945
- body: JSON.stringify({
946
- key,
947
- value,
948
- is_secret: isSecret
949
- })
950
- });
951
- if (!res.ok) {
952
- const errorBody = await res.text();
953
- if (res.status === 401) console.error("[wawesome] Error: Authentication expired. Run 'wawesome login' again.");
954
- else {
955
- let msg = `HTTP ${res.status}`;
956
- try {
957
- const parsed = JSON.parse(errorBody);
958
- if (parsed.error) msg = parsed.error;
959
- } catch {}
960
- console.error(`[wawesome] Error: Failed to set variable '${key}' (${msg}).`);
961
- if (isVerbose) console.error(`[wawesome:verbose] Response: ${errorBody}`);
962
- }
963
- process.exit(1);
964
- }
965
- const data = await res.json();
966
- if (data.variable.is_secret || isSecret) {
967
- console.log(`\n[wawesome] ✅ Set secret variable '${key}' on app '${app}'.`);
968
- const messages = data.notice?.messages?.length ? data.notice.messages : STANDARD_SECRET_MESSAGES;
969
- console.log("\n🔒 \x1B[1mSecret Notice:\x1B[0m");
970
- for (const msg of messages) console.log(` • ${msg}`);
971
- console.log("");
972
- } else console.log(`[wawesome] ✅ Set variable '${key}' on app '${app}'.`);
973
- }
974
- function truncate(str, maxLen) {
975
- if (str.length <= maxLen) return str;
976
- if (maxLen <= 3) return str.slice(0, maxLen);
977
- return str.slice(0, maxLen - 1) + "…";
978
- }
979
- /**
980
- * List environment variables on the current app.
981
- */
982
- async function listEnvVars(options) {
983
- const isVerbose = Boolean(options.verbose);
984
- const { creds, app } = loadClientContext();
985
- const url = `${creds.gateway_url}/v1/apps/${encodeURIComponent(app)}/env`;
986
- if (isVerbose) console.log(`[wawesome:verbose] GET ${url}`);
987
- const res = await fetch(url, {
988
- method: "GET",
989
- headers: { Authorization: `Bearer ${creds.tenant_jwt}` }
990
- });
991
- if (!res.ok) {
992
- const errorBody = await res.text();
993
- if (res.status === 401) console.error("[wawesome] Error: Authentication expired. Run 'wawesome login' again.");
994
- else {
995
- console.error(`[wawesome] Error: Failed to list variables (HTTP ${res.status}).`);
996
- if (isVerbose) console.error(`[wawesome:verbose] Response: ${errorBody}`);
997
- }
998
- process.exit(1);
999
- }
1000
- const data = await res.json();
1001
- if (!data.variables || data.variables.length === 0) {
1002
- console.log(`[wawesome] No environment variables set for app '${app}'.`);
1003
- return;
1004
- }
1005
- const availableWidth = (process.stdout.columns && process.stdout.columns > 40 ? process.stdout.columns : 80) - 12;
1006
- let rawMaxKeyLen = 15;
1007
- let rawMaxValLen = 15;
1008
- for (const item of data.variables) {
1009
- if (item.key.length > rawMaxKeyLen) rawMaxKeyLen = item.key.length;
1010
- if (item.value.length > rawMaxValLen) rawMaxValLen = item.value.length;
1011
- }
1012
- const maxKeyLen = Math.min(rawMaxKeyLen, Math.max(15, Math.floor(availableWidth * .4)));
1013
- const maxValLen = Math.min(rawMaxValLen, Math.max(15, availableWidth - maxKeyLen));
1014
- console.log(`\n📋 \x1b[1mEnvironment variables for '${app}'\x1b[0m\n`);
1015
- const headerKey = "KEY".padEnd(maxKeyLen);
1016
- const headerVal = "VALUE".padEnd(maxValLen);
1017
- console.log(`${headerKey} | ${headerVal} | SECRET`);
1018
- console.log(`${"-".repeat(maxKeyLen)}-|- ${"-".repeat(maxValLen)} |-------`);
1019
- for (const item of data.variables) {
1020
- const truncatedKey = truncate(item.key, maxKeyLen);
1021
- const truncatedVal = truncate(item.value, maxValLen);
1022
- const keyStr = truncatedKey.padEnd(maxKeyLen);
1023
- const valStr = truncatedVal.padEnd(maxValLen);
1024
- const secretStr = item.is_secret ? "\x1B[33mtrue\x1B[0m" : "false";
1025
- console.log(`${keyStr} | ${valStr} | ${secretStr}`);
1026
- }
1027
- console.log("");
1028
- }
1029
- /**
1030
- * Delete an environment variable on the current app.
1031
- */
1032
- async function removeEnvVar(key, options) {
1033
- const isVerbose = Boolean(options.verbose);
1034
- if (!key) {
1035
- console.error("[wawesome] Error: Missing variable key. Usage: wawesome env rm <KEY>");
1036
- process.exit(1);
1037
- }
1038
- const { creds, app } = loadClientContext();
1039
- const url = `${creds.gateway_url}/v1/apps/${encodeURIComponent(app)}/env/${encodeURIComponent(key)}`;
1040
- if (isVerbose) console.log(`[wawesome:verbose] DELETE ${url}`);
1041
- const res = await fetch(url, {
1042
- method: "DELETE",
1043
- headers: { Authorization: `Bearer ${creds.tenant_jwt}` }
1044
- });
1045
- if (!res.ok) {
1046
- const errorBody = await res.text();
1047
- if (res.status === 401) console.error("[wawesome] Error: Authentication expired. Run 'wawesome login' again.");
1048
- else if (res.status === 404) console.error(`[wawesome] Error: Variable '${key}' not found on app '${app}'.`);
1049
- else {
1050
- console.error(`[wawesome] Error: Failed to delete variable '${key}' (HTTP ${res.status}).`);
1051
- if (isVerbose) console.error(`[wawesome:verbose] Response: ${errorBody}`);
1052
- }
1053
- process.exit(1);
1054
- }
1055
- console.log(`[wawesome] ✅ Deleted variable '${key}' from app '${app}'.`);
1056
- }
1057
- /**
1058
- * Dispatcher function for `wawesome env` CLI command.
1059
- */
1060
- async function envCommand(action, key, value, options) {
1061
- if (!action || action === "list" || action === "ls") return listEnvVars(options);
1062
- if (action === "set") return setEnvVar(key, value, options);
1063
- if (action === "rm" || action === "remove" || action === "delete" || action === "unset") return removeEnvVar(key, options);
1064
- console.error(`[wawesome] Error: Unknown env action '${action}'. Available actions: list, set, rm.`);
1065
- process.exit(1);
1066
- }
1067
- //#endregion
1068
1677
  //#region src/logs.ts
1069
1678
  const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1070
1679
  function isUuid(str) {
@@ -1669,7 +2278,8 @@ cli.command("login", "Authenticate with the wawesome.io platform").option("--api
1669
2278
  cli.command("logout", "Clear stored authentication credentials").action(() => logout());
1670
2279
  cli.command("whoami", "Show current login session info").action(() => whoami());
1671
2280
  cli.command("workspace [action] [name]", "Show the workspace, or rename its public address").usage("workspace <action> [name]\n\nActions:\n show Show the workspace name, address, and whether it can still change\n rename <name> Change the public address, while nothing live depends on it").example("wawesome workspace").example("wawesome workspace rename northwind").option("-v, --verbose", "Enable verbose debug output").action((action, name, options) => workspaceCommand(action, name, options));
1672
- cli.command("init", "Scaffold a new function project in the current directory").option("-v, --verbose", "Enable verbose debug output").action((options) => init(options));
2281
+ cli.command("templates [action]", "Browse the template catalog").usage("templates [action]\n\nActions:\n list (ls) Show every available template (default)").example("wawesome templates").example("wawesome templates list").option("--api <url>", "API URL (default: https://api.wawesome.io)").option("-v, --verbose", "Enable verbose debug output").action((action, options) => templatesCommand(action, options));
2282
+ cli.command("init", "Scaffold a new function project in the current directory").usage("init [options]\n\nWith --template, the project is fetched from the template catalog, wired up\nfrom what the template declares it needs, and deployed. Run 'wawesome templates'\nto see what is available.").example("wawesome init").example("wawesome init --template stripe-webhook").option("-t, --template <name>", "Scaffold from a catalog template and deploy it").option("--api <url>", "API URL (default: https://api.wawesome.io)").option("-v, --verbose", "Enable verbose debug output").action((options) => init(options));
1673
2283
  cli.command("logs [function-name-or-invocation-id]", "View invocation history, fetch log output, or follow live").usage(`logs [target] [options]
1674
2284
 
1675
2285
  The target argument determines what the command does: