@keystrokehq/cli 0.1.17 → 0.1.19
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/{dist-C6KqfgGN.mjs → dist-5F59cW3X.mjs} +3 -3
- package/dist/dist-5F59cW3X.mjs.map +1 -0
- package/dist/{dist-E9nHDRnf.mjs → dist-BYODo4g3.mjs} +2103 -1498
- package/dist/dist-BYODo4g3.mjs.map +1 -0
- package/dist/dist-CJ2FFTtR.mjs +3 -0
- package/dist/{dist-BRA_tOTT.mjs → dist-DmqYCJqU.mjs} +26 -2
- package/dist/{dist-BRA_tOTT.mjs.map → dist-DmqYCJqU.mjs.map} +1 -1
- package/dist/{dist-DeRE4uJW.mjs → dist-QE1G9hAR.mjs} +2 -2
- package/dist/{dist-DeRE4uJW.mjs.map → dist-QE1G9hAR.mjs.map} +1 -1
- package/dist/index.mjs +109 -17
- package/dist/index.mjs.map +1 -1
- package/dist/{maybe-auto-update-douMZFWJ.mjs → maybe-auto-update-DVsgC8Cq.mjs} +2 -2
- package/dist/{maybe-auto-update-douMZFWJ.mjs.map → maybe-auto-update-DVsgC8Cq.mjs.map} +1 -1
- package/dist/skills-bundle/_AGENTS.md +2 -0
- package/dist/skills-bundle/skills/keystroke-agents/SKILL.md +2 -2
- package/dist/skills-bundle/skills/keystroke-agents/references/tools-mcp-codemode.md +2 -2
- package/dist/skills-bundle/skills/keystroke-apps/SKILL.md +5 -0
- package/dist/skills-bundle/skills/keystroke-apps/references/cli-and-catalog.md +9 -2
- package/dist/skills-bundle/skills/keystroke-cli/SKILL.md +13 -0
- package/dist/skills-bundle/skills/keystroke-workflows/SKILL.md +1 -1
- package/dist/skills-bundle/skills/keystroke-workflows/references/authoring.md +3 -3
- package/dist/templates/hello-world/src/agents/hello.ts +1 -1
- package/dist/{version-CJd1mEoq.mjs → version-BudDbxko.mjs} +2 -2
- package/dist/{version-CJd1mEoq.mjs.map → version-BudDbxko.mjs.map} +1 -1
- package/package.json +2 -3
- package/dist/dist-BZBvPUyu.mjs +0 -3
- package/dist/dist-C6KqfgGN.mjs.map +0 -1
- package/dist/dist-E9nHDRnf.mjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
2
|
+
import { qn as parseStoredRouteManifest, qt as ROUTE_MANIFEST_REL_PATH } from "./dist-DmqYCJqU.mjs";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
@@ -124,4 +124,4 @@ async function mapInParallelBatches(items, batchSize, fn) {
|
|
|
124
124
|
//#endregion
|
|
125
125
|
export { mergeFilteredArtifact as n, packProjectArtifact as r, mapInParallelBatches as t };
|
|
126
126
|
|
|
127
|
-
//# sourceMappingURL=dist-
|
|
127
|
+
//# sourceMappingURL=dist-QE1G9hAR.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dist-DeRE4uJW.mjs","names":[],"sources":["../../../packages/storage/dist/pack-artifact-DVnIKrsg.mjs","../../../packages/storage/dist/index.mjs"],"sourcesContent":["import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\nimport { tmpdir } from \"node:os\";\nimport { ROUTE_MANIFEST_REL_PATH, parseStoredRouteManifest } from \"@keystrokehq/shared\";\n//#region src/pack-dir.ts\n/**\n* Pack a directory tree that contains a `dist/` folder into a gzip tarball\n* suitable for project-server extraction.\n*/\nfunction packDistTree(rootContainingDist) {\n\tconst tempDir = mkdtempSync(join(tmpdir(), \"keystroke-artifact-pack-\"));\n\tconst archivePath = join(tempDir, \"artifact.tgz\");\n\ttry {\n\t\tconst result = spawnSync(\"tar\", [\n\t\t\t\"-czf\",\n\t\t\tarchivePath,\n\t\t\t\"--exclude=._*\",\n\t\t\t\"--exclude=.DS_Store\",\n\t\t\t\"-C\",\n\t\t\trootContainingDist,\n\t\t\t\"dist\"\n\t\t], {\n\t\t\tencoding: \"utf8\",\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\tCOPYFILE_DISABLE: \"1\"\n\t\t\t}\n\t\t});\n\t\tif (result.status !== 0) throw new Error(result.stderr?.trim() || \"Failed to pack project artifact\");\n\t\treturn readFileSync(archivePath);\n\t} finally {\n\t\trmSync(tempDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/extract-artifact.ts\n/** Extract a packed project artifact tarball into `destDir` (creates `destDir/dist/`). */\nfunction extractProjectArtifact(archive, destDir) {\n\tconst tempDir = mkdtempSync(join(tmpdir(), \"keystroke-artifact-extract-\"));\n\tconst archivePath = join(tempDir, \"artifact.tgz\");\n\ttry {\n\t\twriteFileSync(archivePath, archive);\n\t\tconst result = spawnSync(\"tar\", [\n\t\t\t\"-xzf\",\n\t\t\tarchivePath,\n\t\t\t\"-C\",\n\t\t\tdestDir\n\t\t], {\n\t\t\tencoding: \"utf8\",\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\tCOPYFILE_DISABLE: \"1\"\n\t\t\t}\n\t\t});\n\t\tif (result.status !== 0) throw new Error(result.stderr?.trim() || \"Failed to extract project artifact\");\n\t} finally {\n\t\trmSync(tempDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/merge-route-manifest.ts\nfunction moduleFileOf(entry) {\n\treturn \"moduleFile\" in entry && typeof entry.moduleFile === \"string\" ? entry.moduleFile : void 0;\n}\n/** Replace manifest rows for rebuilt modules while keeping untouched routes and metadata. */\nfunction mergeStoredRouteManifest(base, rebuiltEntries) {\n\tconst rebuiltModuleFiles = new Set(rebuiltEntries.map(moduleFileOf).filter((value) => Boolean(value)));\n\tconst keptEntries = base.entries.filter((entry) => {\n\t\tconst moduleFile = moduleFileOf(entry);\n\t\tif (!moduleFile) return true;\n\t\treturn !rebuiltModuleFiles.has(moduleFile);\n\t});\n\tconst filteredRebuilt = rebuiltEntries.filter((entry) => entry.kind !== \"health\");\n\treturn {\n\t\t...base,\n\t\tentries: [...keptEntries, ...filteredRebuilt]\n\t};\n}\n//#endregion\n//#region src/merge-filtered-artifact.ts\nasync function mergeFilteredArtifact(input) {\n\tconst mergeRoot = mkdtempSync(join(tmpdir(), \"keystroke-artifact-merge-\"));\n\ttry {\n\t\textractProjectArtifact(input.baseArchive, mergeRoot);\n\t\tconst manifestPath = join(mergeRoot, ROUTE_MANIFEST_REL_PATH);\n\t\tconst mergedManifest = mergeStoredRouteManifest(parseStoredRouteManifest(JSON.parse(readFileSync(manifestPath, \"utf8\"))), input.filtered.manifestEntries);\n\t\twriteFileSync(manifestPath, `${JSON.stringify(mergedManifest, null, 2)}\\n`);\n\t\tfor (const file of input.filtered.files) {\n\t\t\tconst destination = join(mergeRoot, \"dist\", file.relativePath);\n\t\t\tmkdirSync(dirname(destination), { recursive: true });\n\t\t\twriteFileSync(destination, file.contents);\n\t\t\tif (file.sourceMap) writeFileSync(`${destination}.map`, file.sourceMap);\n\t\t}\n\t\treturn packDistTree(mergeRoot);\n\t} finally {\n\t\trmSync(mergeRoot, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/pack-artifact.ts\n/** Pack `dist/` into a gzip tarball suitable for `/app` extraction in the project server image. */\nfunction packProjectArtifact(projectRoot) {\n\tif (!existsSync(join(projectRoot, \"dist\"))) throw new Error(\"dist/ not found — run keystroke build first\");\n\treturn packDistTree(projectRoot);\n}\n//#endregion\nexport { packDistTree as a, extractProjectArtifact as i, mergeFilteredArtifact as n, mergeStoredRouteManifest as r, packProjectArtifact as t };\n\n//# sourceMappingURL=pack-artifact-DVnIKrsg.mjs.map","import { a as packDistTree, i as extractProjectArtifact, n as mergeFilteredArtifact, r as mergeStoredRouteManifest, t as packProjectArtifact } from \"./pack-artifact-DVnIKrsg.mjs\";\nimport { CreateBucketCommand, DeleteBucketCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutBucketAclCommand, PutBucketPolicyCommand, PutObjectCommand, S3Client } from \"@aws-sdk/client-s3\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\nimport { tmpdir } from \"node:os\";\nimport { ROUTE_MANIFEST_REL_PATH } from \"@keystrokehq/shared\";\nimport { createHash } from \"node:crypto\";\n//#region src/config.ts\nfunction readEnv$1(env, ...keys) {\n\tfor (const key of keys) {\n\t\tconst value = env[key]?.trim();\n\t\tif (value) return value;\n\t}\n}\nfunction requireEnv(env, keys) {\n\tconst candidates = Array.isArray(keys) ? keys : [keys];\n\tconst value = readEnv$1(env, ...candidates);\n\tif (!value) throw new Error(`${candidates[0]} is required`);\n\treturn value;\n}\n/** Admin S3 credentials for storage plugins (bucket is per-org, not from env). */\nfunction storageAdminConfigFromEnv(env = process.env) {\n\tconst accessKeyId = requireEnv(env, [\"STORAGE_ACCESS_KEY_ID\", \"AWS_ACCESS_KEY_ID\"]);\n\tconst secretAccessKey = requireEnv(env, [\"STORAGE_SECRET_ACCESS_KEY\", \"AWS_SECRET_ACCESS_KEY\"]);\n\tconst endpoint = requireEnv(env, [\n\t\t\"STORAGE_ENDPOINT\",\n\t\t\"AWS_ENDPOINT_URL_S3\",\n\t\t\"AWS_S3_ENDPOINT\"\n\t]);\n\treturn {\n\t\tregion: readEnv$1(env, \"STORAGE_REGION\", \"AWS_REGION\") ?? \"us-east-1\",\n\t\taccessKeyId,\n\t\tsecretAccessKey,\n\t\tendpoint,\n\t\tforcePathStyle: env.STORAGE_FORCE_PATH_STYLE === void 0 ? true : env.STORAGE_FORCE_PATH_STYLE === \"true\"\n\t};\n}\n/** Full client config including bucket — for integration tests and explicit bucket callers. */\nfunction storageConfigFromEnv(env = process.env) {\n\tconst bucket = requireEnv(env, [\"STORAGE_BUCKET\", \"BUCKET_NAME\"]);\n\treturn {\n\t\t...storageAdminConfigFromEnv(env),\n\t\tbucket\n\t};\n}\n/** Endpoint for presigned URLs fetched inside project-server containers (e.g. `http://minio:9000`). */\nfunction containerPresignEndpointFromEnv(hostEndpoint, env = process.env) {\n\tconst override = readEnv$1(env, \"STORAGE_CONTAINER_ENDPOINT\");\n\tif (override) return override;\n\ttry {\n\t\tconst url = new URL(hostEndpoint);\n\t\tif (url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\") {\n\t\t\tconst port = url.port || (url.protocol === \"https:\" ? \"443\" : \"9000\");\n\t\t\treturn `${url.protocol}//minio:${port}`;\n\t\t}\n\t} catch {}\n\treturn hostEndpoint;\n}\n//#endregion\n//#region src/keys.ts\n/** Object key for a built project artifact tarball. */\nfunction projectArtifactKey(projectId, version) {\n\treturn `projects/${projectId}/artifacts/${version}.tgz`;\n}\n/**\n* Per-artifact source manifest (the deploy's file tree: path -> id + content\n* hash, plus resource refs). One per deploy.\n*/\nfunction projectSourceManifestKey(projectId, artifactId) {\n\treturn `projects/${projectId}/sources/${artifactId}/index.json`;\n}\nconst SHA256_HEX = /^[a-f0-9]{64}$/;\n/** True when `hash` is a lowercase hex sha256 digest (64 chars). */\nfunction isSourceBlobHash(hash) {\n\treturn SHA256_HEX.test(hash);\n}\n/**\n* Content-addressed key for a single source file's contents, deduped across all\n* of a project's deploys. `hash` is a lowercase hex sha256 of the file bytes.\n*/\nfunction projectSourceBlobKey(projectId, hash) {\n\tif (!isSourceBlobHash(hash)) throw new Error(\"Invalid source blob hash\");\n\treturn `projects/${projectId}/sources/blobs/${hash}`;\n}\nconst AVATAR_EXTENSION = /^[a-z0-9]+$/;\n/** Object key for a chat attachment in org-private storage. */\nfunction chatAttachmentStorageKey(projectId, id, ext) {\n\tconst normalizedExt = ext.replace(/^\\./, \"\").toLowerCase();\n\tif (!AVATAR_EXTENSION.test(normalizedExt)) throw new Error(\"Invalid chat attachment extension\");\n\treturn `chat-attachments/${projectId}/${id}.${normalizedExt}`;\n}\n/** True when `key` is a chat attachment owned by `projectId`. */\nfunction isChatAttachmentStorageKey(key, projectId) {\n\tconst prefix = `chat-attachments/${projectId}/`;\n\tif (!key.startsWith(prefix)) return false;\n\tconst remainder = key.slice(prefix.length);\n\treturn remainder.length > 0 && !remainder.includes(\"/\");\n}\n/** Object key for a user's custom profile avatar in the shared keystroke-users bucket. */\nfunction userAvatarStorageKey(userId, extension) {\n\tconst ext = extension.replace(/^\\./, \"\").toLowerCase();\n\tif (!AVATAR_EXTENSION.test(ext)) throw new Error(\"Invalid avatar extension\");\n\treturn `avatars/${userId}/avatar.${ext}`;\n}\n/** True when `key` is the canonical avatar object for `userId`. */\nfunction isUserAvatarStorageKey(key, userId) {\n\tconst prefix = `avatars/${userId}/avatar.`;\n\tif (!key.startsWith(prefix)) return false;\n\tconst ext = key.slice(prefix.length);\n\treturn AVATAR_EXTENSION.test(ext);\n}\n/** Object key for an org logo in the shared keystroke-assets bucket. */\nfunction orgLogoStorageKey(organizationId, variant, extension) {\n\tconst ext = extension.replace(/^\\./, \"\").toLowerCase();\n\tif (!AVATAR_EXTENSION.test(ext)) throw new Error(\"Invalid org logo extension\");\n\treturn `org-logos/${organizationId}/logo-${variant}.${ext}`;\n}\n/** True when `key` is the canonical logo object for `organizationId` and `variant`. */\nfunction isOrgLogoStorageKey(key, organizationId, variant) {\n\tconst prefix = `org-logos/${organizationId}/logo-${variant}.`;\n\tif (!key.startsWith(prefix)) return false;\n\tconst ext = key.slice(prefix.length);\n\treturn AVATAR_EXTENSION.test(ext);\n}\n//#endregion\n//#region src/map-in-batches.ts\n/** Default concurrency for parallel blob downloads and file writes. */\nconst DEFAULT_PARALLEL_BATCH_SIZE = 8;\n/** Run `fn` over `items` in parallel batches of `batchSize`. */\nasync function mapInParallelBatches(items, batchSize, fn) {\n\tif (batchSize < 1) throw new Error(\"batchSize must be at least 1\");\n\tconst results = [];\n\tfor (let index = 0; index < items.length; index += batchSize) {\n\t\tconst batch = items.slice(index, index + batchSize);\n\t\tresults.push(...await Promise.all(batch.map(fn)));\n\t}\n\treturn results;\n}\n//#endregion\n//#region src/load-project-source-files.ts\n/** Matches deploy-time source snapshot limits in @keystrokehq/build walk-project. */\nconst MAX_ACTIVE_SOURCE_DOWNLOAD_BYTES = 8 * 1024 * 1024;\nasync function loadProjectSourceFiles(storage, projectId, manifest, options = {}) {\n\tconst maxTotalBytes = options.maxTotalBytes ?? 8388608;\n\tconst files = [];\n\tlet totalBytes = 0;\n\tfor (let index = 0; index < manifest.files.length; index += 8) {\n\t\tconst batch = manifest.files.slice(index, index + 8);\n\t\tconst batchResults = await Promise.all(batch.map(async (file) => {\n\t\t\tconst bytes = await storage.getObject(projectSourceBlobKey(projectId, file.hash));\n\t\t\tconst contents = new TextDecoder().decode(bytes);\n\t\t\treturn {\n\t\t\t\tpath: file.path,\n\t\t\t\tcontents,\n\t\t\t\tbyteLength: Buffer.byteLength(contents, \"utf8\")\n\t\t\t};\n\t\t}));\n\t\tfor (const result of batchResults) {\n\t\t\ttotalBytes += result.byteLength;\n\t\t\tif (totalBytes > maxTotalBytes) throw new Error(\"Active source snapshot exceeds download size limit\");\n\t\t\tfiles.push({\n\t\t\t\tpath: result.path,\n\t\t\t\tcontents: result.contents\n\t\t\t});\n\t\t}\n\t}\n\treturn files;\n}\n//#endregion\n//#region src/create-storage.ts\nconst DEFAULT_PRESIGN_TTL_SECONDS = 900;\nfunction createStorage(config) {\n\tconst client = new S3Client(toClientConfig(config));\n\treturn {\n\t\tasync putObject(input) {\n\t\t\tawait client.send(new PutObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: input.key,\n\t\t\t\tBody: input.body,\n\t\t\t\tContentType: input.contentType\n\t\t\t}));\n\t\t},\n\t\tasync getObject(key) {\n\t\t\tconst response = await client.send(new GetObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: key\n\t\t\t}));\n\t\t\tif (!response.Body) throw new Error(`Object body missing for key ${key}`);\n\t\t\treturn response.Body.transformToByteArray();\n\t\t},\n\t\tasync headObject(key) {\n\t\t\ttry {\n\t\t\t\treturn { contentLength: (await client.send(new HeadObjectCommand({\n\t\t\t\t\tBucket: config.bucket,\n\t\t\t\t\tKey: key\n\t\t\t\t}))).ContentLength ?? 0 };\n\t\t\t} catch (error) {\n\t\t\t\tif (isNotFoundError(error)) return;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tasync presignGet(input) {\n\t\t\treturn getSignedUrl(client, new GetObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: input.key\n\t\t\t}), { expiresIn: input.expiresInSeconds ?? DEFAULT_PRESIGN_TTL_SECONDS });\n\t\t},\n\t\tasync presignPut(input) {\n\t\t\treturn getSignedUrl(client, new PutObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: input.key,\n\t\t\t\tContentType: input.contentType ?? \"application/gzip\"\n\t\t\t}), { expiresIn: input.expiresInSeconds ?? DEFAULT_PRESIGN_TTL_SECONDS });\n\t\t},\n\t\tasync deleteObject(key) {\n\t\t\tawait client.send(new DeleteObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: key\n\t\t\t}));\n\t\t},\n\t\tasync listObjects(prefix) {\n\t\t\tconst keys = [];\n\t\t\tlet continuationToken;\n\t\t\tdo {\n\t\t\t\tconst response = await client.send(new ListObjectsV2Command({\n\t\t\t\t\tBucket: config.bucket,\n\t\t\t\t\tPrefix: prefix,\n\t\t\t\t\tContinuationToken: continuationToken\n\t\t\t\t}));\n\t\t\t\tfor (const object of response.Contents ?? []) if (object.Key) keys.push(object.Key);\n\t\t\t\tcontinuationToken = response.IsTruncated ? response.NextContinuationToken : void 0;\n\t\t\t} while (continuationToken);\n\t\t\treturn keys;\n\t\t}\n\t};\n}\n/** Presign URLs for project-server containers using `STORAGE_CONTAINER_ENDPOINT` when set. */\nfunction createContainerPresignStorage(config, env = process.env) {\n\treturn createStorage({\n\t\t...config,\n\t\tendpoint: containerPresignEndpointFromEnv(config.endpoint, env)\n\t});\n}\nfunction toClientConfig(config) {\n\treturn {\n\t\tregion: config.region,\n\t\tcredentials: {\n\t\t\taccessKeyId: config.accessKeyId,\n\t\t\tsecretAccessKey: config.secretAccessKey\n\t\t},\n\t\tendpoint: config.endpoint,\n\t\tforcePathStyle: config.forcePathStyle\n\t};\n}\nfunction isNotFoundError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst name = \"name\" in error ? String(error.name) : \"\";\n\tconst status = \"$metadata\" in error ? error.$metadata : void 0;\n\treturn name === \"NotFound\" || name === \"NoSuchKey\" || status?.httpStatusCode === 404;\n}\n//#endregion\n//#region src/extract-route-manifest.ts\nvar RouteManifestNotFoundError = class extends Error {\n\tconstructor(message = `Route manifest missing in artifact (${ROUTE_MANIFEST_REL_PATH})`) {\n\t\tsuper(message);\n\t\tthis.name = \"RouteManifestNotFoundError\";\n\t}\n};\n/** Read `.keystroke/route-manifest.json` from a packed project artifact tarball. */\nfunction extractRouteManifestFromArtifact(archive) {\n\tconst tempDir = mkdtempSync(join(tmpdir(), \"keystroke-artifact-\"));\n\tconst archivePath = join(tempDir, \"artifact.tgz\");\n\ttry {\n\t\twriteFileSync(archivePath, archive);\n\t\tif (spawnSync(\"tar\", [\n\t\t\t\"-xzf\",\n\t\t\tarchivePath,\n\t\t\t\"-C\",\n\t\t\ttempDir,\n\t\t\tROUTE_MANIFEST_REL_PATH\n\t\t], { encoding: \"utf8\" }).status !== 0) throw new RouteManifestNotFoundError();\n\t\tconst raw = readFileSync(join(tempDir, ROUTE_MANIFEST_REL_PATH), \"utf8\");\n\t\treturn JSON.parse(raw);\n\t} catch (error) {\n\t\tif (error instanceof RouteManifestNotFoundError) throw error;\n\t\tthrow new RouteManifestNotFoundError(error instanceof Error ? error.message : \"Failed to extract route manifest\");\n\t} finally {\n\t\trmSync(tempDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/s3-errors.ts\nfunction isBucketAlreadyExistsError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst name = \"name\" in error ? String(error.name) : \"\";\n\tconst code = \"Code\" in error ? String(error.Code) : \"\";\n\treturn name === \"BucketAlreadyOwnedByYou\" || code === \"BucketAlreadyOwnedByYou\" || name === \"BucketAlreadyExists\" || code === \"BucketAlreadyExists\";\n}\nfunction isStorageNotFoundError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst record = error;\n\tconst name = typeof record.name === \"string\" ? record.name : \"\";\n\tconst code = typeof record.Code === \"string\" ? record.Code : \"\";\n\tconst status = typeof record.$metadata === \"object\" && record.$metadata !== null ? record.$metadata.httpStatusCode : void 0;\n\treturn name === \"NoSuchKey\" || code === \"NoSuchKey\" || code === \"NotFound\" || status === 404;\n}\nfunction isStorageBucketNotFoundError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst record = error;\n\tconst name = typeof record.name === \"string\" ? record.name : \"\";\n\tconst code = typeof record.Code === \"string\" ? record.Code : \"\";\n\tconst status = typeof record.$metadata === \"object\" && record.$metadata !== null ? record.$metadata.httpStatusCode : void 0;\n\treturn name === \"NoSuchBucket\" || code === \"NoSuchBucket\" || name === \"NotFound\" || status === 404;\n}\n//#endregion\n//#region src/asset-storage.ts\n/** Shared bucket for cross-org public assets (avatars, org sidebar logos). */\nconst KEYSTROKE_ASSETS_BUCKET = \"keystroke-assets\";\n/** Env var for the browser-facing origin of public asset objects (no trailing slash). */\nconst KEYSTROKE_ASSETS_PUBLIC_URL_BASE_ENV = \"KEYSTROKE_ASSETS_PUBLIC_URL_BASE\";\nconst KEYSTROKE_ASSETS_AVATAR_PREFIX = \"avatars/\";\nconst KEYSTROKE_ASSETS_ORG_LOGO_PREFIX = \"org-logos/\";\nfunction readEnv(env, key) {\n\treturn env[key]?.trim() || void 0;\n}\n/** Default path-style base when `KEYSTROKE_ASSETS_PUBLIC_URL_BASE` is unset (local MinIO). */\nfunction defaultKeystrokeAssetsPublicUrlBase(env = process.env) {\n\treturn `${storageAdminConfigFromEnv(env).endpoint.replace(/\\/+$/, \"\")}/${KEYSTROKE_ASSETS_BUCKET}`;\n}\n/** Public URL prefix for asset objects — configured base or local path-style default. */\nfunction keystrokeAssetsPublicUrlBase(env = process.env) {\n\tconst configured = readEnv(env, KEYSTROKE_ASSETS_PUBLIC_URL_BASE_ENV);\n\tif (configured) return configured.replace(/\\/+$/, \"\");\n\treturn defaultKeystrokeAssetsPublicUrlBase(env);\n}\nfunction keystrokeAssetsPublicUrlPrefixes(env = process.env) {\n\tconst prefixes = [keystrokeAssetsPublicUrlBase(env)];\n\tif (readEnv(env, \"KEYSTROKE_ASSETS_PUBLIC_URL_BASE\")) prefixes.push(defaultKeystrokeAssetsPublicUrlBase(env));\n\treturn [...new Set(prefixes)];\n}\nfunction createAssetsStorageClient(env = process.env) {\n\treturn createStorage({\n\t\t...storageAdminConfigFromEnv(env),\n\t\tbucket: KEYSTROKE_ASSETS_BUCKET\n\t});\n}\n/** Stable public URL for an object in the keystroke-assets bucket. */\nfunction publicKeystrokeAssetsObjectUrl(key, env = process.env) {\n\treturn `${keystrokeAssetsPublicUrlBase(env)}/${key}`;\n}\n/** Extract the object key from a public keystroke-assets URL when it matches `requiredPrefix`. */\nfunction keystrokeAssetsKeyFromPublicUrl(url, requiredPrefix, env = process.env) {\n\tfor (const prefix of keystrokeAssetsPublicUrlPrefixes(env)) {\n\t\tconst normalizedPrefix = `${prefix.replace(/\\/+$/, \"\")}/`;\n\t\tif (!url.startsWith(normalizedPrefix)) continue;\n\t\tconst key = decodeURIComponent(url.slice(normalizedPrefix.length).split(\"?\")[0] ?? \"\");\n\t\tif (key.startsWith(requiredPrefix)) return key;\n\t}\n\treturn null;\n}\nfunction isKeystrokeAssetsAvatarPublicUrl(url, env = process.env) {\n\treturn keystrokeAssetsKeyFromPublicUrl(url, KEYSTROKE_ASSETS_AVATAR_PREFIX, env) !== null;\n}\nfunction keystrokeAssetsAvatarKeyFromPublicUrl(url, env = process.env) {\n\treturn keystrokeAssetsKeyFromPublicUrl(url, KEYSTROKE_ASSETS_AVATAR_PREFIX, env);\n}\nfunction isKeystrokeAssetsOrgLogoPublicUrl(url, env = process.env) {\n\treturn keystrokeAssetsKeyFromPublicUrl(url, KEYSTROKE_ASSETS_ORG_LOGO_PREFIX, env) !== null;\n}\nfunction keystrokeAssetsOrgLogoKeyFromPublicUrl(url, env = process.env) {\n\treturn keystrokeAssetsKeyFromPublicUrl(url, KEYSTROKE_ASSETS_ORG_LOGO_PREFIX, env);\n}\nasync function ensureKeystrokeAssetsBucket(env = process.env) {\n\tconst adminConfig = storageAdminConfigFromEnv(env);\n\tconst adminClient = new S3Client({\n\t\tregion: adminConfig.region,\n\t\tcredentials: {\n\t\t\taccessKeyId: adminConfig.accessKeyId,\n\t\t\tsecretAccessKey: adminConfig.secretAccessKey\n\t\t},\n\t\tendpoint: adminConfig.endpoint,\n\t\tforcePathStyle: adminConfig.forcePathStyle\n\t});\n\tawait createAssetsBucketIfNeeded(adminClient, KEYSTROKE_ASSETS_BUCKET);\n\tawait applyPublicAssetsBucketAcl(adminClient, KEYSTROKE_ASSETS_BUCKET);\n\tawait applyPublicAssetsBucketPolicy(adminClient, KEYSTROKE_ASSETS_BUCKET);\n}\nasync function createAssetsBucketIfNeeded(adminClient, bucket) {\n\ttry {\n\t\tawait adminClient.send(new CreateBucketCommand({\n\t\t\tBucket: bucket,\n\t\t\tACL: \"public-read\"\n\t\t}));\n\t\treturn;\n\t} catch (error) {\n\t\tif (isBucketAlreadyExistsError(error)) return;\n\t}\n\ttry {\n\t\tawait adminClient.send(new CreateBucketCommand({ Bucket: bucket }));\n\t} catch (error) {\n\t\tif (!isBucketAlreadyExistsError(error)) throw error;\n\t}\n}\nasync function applyPublicAssetsBucketAcl(adminClient, bucket) {\n\ttry {\n\t\tawait adminClient.send(new PutBucketAclCommand({\n\t\t\tBucket: bucket,\n\t\t\tACL: \"public-read\"\n\t\t}));\n\t} catch (error) {\n\t\tif (!isUnsupportedStorageFeatureError(error)) console.warn(\"[storage] PutBucketAcl failed (continuing):\", error);\n\t}\n}\nasync function applyPublicAssetsBucketPolicy(adminClient, bucket) {\n\ttry {\n\t\tawait adminClient.send(new PutBucketPolicyCommand({\n\t\t\tBucket: bucket,\n\t\t\tPolicy: JSON.stringify({\n\t\t\t\tVersion: \"2012-10-17\",\n\t\t\t\tStatement: [{\n\t\t\t\t\tEffect: \"Allow\",\n\t\t\t\t\tPrincipal: \"*\",\n\t\t\t\t\tAction: [\"s3:GetObject\"],\n\t\t\t\t\tResource: [`arn:aws:s3:::${bucket}/${KEYSTROKE_ASSETS_AVATAR_PREFIX}*`, `arn:aws:s3:::${bucket}/${KEYSTROKE_ASSETS_ORG_LOGO_PREFIX}*`]\n\t\t\t\t}]\n\t\t\t})\n\t\t}));\n\t} catch (error) {\n\t\tif (!isUnsupportedStorageFeatureError(error)) console.warn(\"[storage] PutBucketPolicy failed (continuing):\", error);\n\t}\n}\nfunction isUnsupportedStorageFeatureError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst name = \"name\" in error ? String(error.name) : \"\";\n\tconst code = \"Code\" in error ? String(error.Code) : \"\";\n\treturn name === \"NotImplemented\" || code === \"NotImplemented\" || code === \"NotSupported\";\n}\n//#endregion\n//#region src/provision/names.ts\nconst DEFAULT_BUCKET_NAME_PREFIX = \"ks\";\nconst S3_BUCKET_NAME_MAX = 63;\n/** Deterministic bucket segment; keeps short test ids readable, hashes UUID-length ids. */\nfunction bucketIdSegment(id, hashLength = 10) {\n\tif (id.length <= 24 && !/^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(id)) return id;\n\treturn createHash(\"sha256\").update(id).digest(\"hex\").slice(0, hashLength);\n}\nfunction assertBucketName(name) {\n\tif (name.length > S3_BUCKET_NAME_MAX) throw new Error(`bucket name exceeds ${S3_BUCKET_NAME_MAX} chars (${name.length}): ${name}`);\n\treturn name;\n}\nfunction orgStorageBucketName(input, prefix = DEFAULT_BUCKET_NAME_PREFIX) {\n\treturn assertBucketName(`${prefix.trim().replace(/-+$/g, \"\")}-${input.organizationId.toLowerCase()}`);\n}\nfunction orgAgentBucketName(input) {\n\tconst orgBucket = input.orgBucket ?? (input.organizationId ? orgStorageBucketName({ organizationId: input.organizationId }) : void 0);\n\tif (!orgBucket) throw new Error(\"orgAgentBucketName requires organizationId or orgBucket\");\n\treturn assertBucketName(`${orgBucket}-${bucketIdSegment(input.agentId)}`);\n}\n//#endregion\n//#region src/workspace/sync.ts\nconst DEFAULT_UPLOAD_CONCURRENCY = 8;\nfunction walkFiles(root) {\n\tconst files = [];\n\tconst stack = [root];\n\twhile (stack.length > 0) {\n\t\tconst current = stack.pop();\n\t\tfor (const entry of readdirSync(current, { withFileTypes: true })) {\n\t\t\tconst full = join(current, entry.name);\n\t\t\tif (entry.isDirectory()) stack.push(full);\n\t\t\telse if (entry.isFile()) files.push(full);\n\t\t}\n\t}\n\treturn files;\n}\nfunction collectWorkspaceObjects(workspaceRoot) {\n\treturn walkFiles(workspaceRoot).map((file) => ({\n\t\tkey: relative(workspaceRoot, file).split(\"\\\\\").join(\"/\"),\n\t\tbody: readFileSync(file)\n\t}));\n}\n/** Keys present in object storage but absent from the local workspace root. */\nfunction workspaceKeysToDelete(remoteKeys, localKeys) {\n\treturn remoteKeys.filter((key) => !localKeys.has(key));\n}\nfunction s3Client(config) {\n\treturn new S3Client({\n\t\tregion: config.region,\n\t\tendpoint: config.endpoint,\n\t\tforcePathStyle: config.forcePathStyle,\n\t\tcredentials: {\n\t\t\taccessKeyId: config.accessKeyId,\n\t\t\tsecretAccessKey: config.secretAccessKey\n\t\t}\n\t});\n}\n/** Create the bucket named in `config` when missing (idempotent for races). */\nasync function ensureStorageBucket(config) {\n\tconst client = s3Client(config);\n\ttry {\n\t\tawait client.send(new CreateBucketCommand({ Bucket: config.bucket }));\n\t} catch (error) {\n\t\tif (!isBucketAlreadyExistsError(error)) throw error;\n\t}\n}\nasync function uploadWorkspaceObjects(config, objects, concurrency = DEFAULT_UPLOAD_CONCURRENCY) {\n\tif (objects.length === 0) return;\n\tconst client = s3Client(config);\n\tlet index = 0;\n\tasync function worker() {\n\t\twhile (index < objects.length) {\n\t\t\tconst current = objects[index++];\n\t\t\tawait client.send(new PutObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: current.key,\n\t\t\t\tBody: current.body\n\t\t\t}));\n\t\t}\n\t}\n\tconst workers = Array.from({ length: Math.min(concurrency, objects.length) }, () => worker());\n\tawait Promise.all(workers);\n}\nasync function deleteWorkspaceObjects(config, keys, concurrency = DEFAULT_UPLOAD_CONCURRENCY) {\n\tif (keys.length === 0) return;\n\tconst client = s3Client(config);\n\tlet index = 0;\n\tasync function worker() {\n\t\twhile (index < keys.length) {\n\t\t\tconst key = keys[index++];\n\t\t\tawait client.send(new DeleteObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: key\n\t\t\t}));\n\t\t}\n\t}\n\tconst workers = Array.from({ length: Math.min(concurrency, keys.length) }, () => worker());\n\tawait Promise.all(workers);\n}\n/** Mirror the host agent workspace directory to the per-agent bucket (upsert + delete stale keys). */\nasync function syncAgentWorkspaceToBucket(input) {\n\tconst bucket = orgAgentBucketName({\n\t\torgBucket: input.orgBucket,\n\t\tagentId: input.agentId\n\t});\n\tconst config = {\n\t\t...input.admin,\n\t\tbucket\n\t};\n\tawait ensureStorageBucket(config);\n\tconst objects = collectWorkspaceObjects(input.agentRoot);\n\tconst localKeys = new Set(objects.map((object) => object.key));\n\tawait deleteWorkspaceObjects(config, workspaceKeysToDelete(await createStorage(config).listObjects(\"\"), localKeys));\n\tawait uploadWorkspaceObjects(config, objects);\n}\n//#endregion\n//#region src/provision/minio.ts\nfunction minioStoragePlugin(options = {}) {\n\tconst adminConfig = storageAdminConfigFromEnv(options.env ?? process.env);\n\tconst adminClient = new S3Client({\n\t\tregion: adminConfig.region,\n\t\tcredentials: {\n\t\t\taccessKeyId: adminConfig.accessKeyId,\n\t\t\tsecretAccessKey: adminConfig.secretAccessKey\n\t\t},\n\t\tendpoint: adminConfig.endpoint,\n\t\tforcePathStyle: adminConfig.forcePathStyle\n\t});\n\treturn {\n\t\tasync provisionOrganization(input) {\n\t\t\tconst bucket = orgStorageBucketName(input, options.bucketNamePrefix);\n\t\t\ttry {\n\t\t\t\tawait adminClient.send(new CreateBucketCommand({ Bucket: bucket }));\n\t\t\t} catch (error) {\n\t\t\t\tif (!isBucketAlreadyExistsError(error)) throw error;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbucket,\n\t\t\t\tendpoint: adminConfig.endpoint,\n\t\t\t\taccessKeyId: adminConfig.accessKeyId,\n\t\t\t\tsecretAccessKey: adminConfig.secretAccessKey,\n\t\t\t\tregion: adminConfig.region,\n\t\t\t\tforcePathStyle: adminConfig.forcePathStyle\n\t\t\t};\n\t\t},\n\t\tasync deprovisionOrganization(result) {\n\t\t\tconst client = new S3Client({\n\t\t\t\tregion: result.region ?? adminConfig.region,\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: result.accessKeyId,\n\t\t\t\t\tsecretAccessKey: result.secretAccessKey\n\t\t\t\t},\n\t\t\t\tendpoint: result.endpoint,\n\t\t\t\tforcePathStyle: result.forcePathStyle ?? true\n\t\t\t});\n\t\t\tif (((await client.send(new ListObjectsV2Command({\n\t\t\t\tBucket: result.bucket,\n\t\t\t\tMaxKeys: 1\n\t\t\t}))).KeyCount ?? 0) > 0) throw new Error(`Refusing to delete non-empty storage bucket ${result.bucket}`);\n\t\t\tawait client.send(new DeleteBucketCommand({ Bucket: result.bucket }));\n\t\t}\n\t};\n}\n//#endregion\nexport { DEFAULT_PARALLEL_BATCH_SIZE, KEYSTROKE_ASSETS_AVATAR_PREFIX, KEYSTROKE_ASSETS_BUCKET, KEYSTROKE_ASSETS_ORG_LOGO_PREFIX, KEYSTROKE_ASSETS_PUBLIC_URL_BASE_ENV, MAX_ACTIVE_SOURCE_DOWNLOAD_BYTES, RouteManifestNotFoundError, bucketIdSegment, chatAttachmentStorageKey, collectWorkspaceObjects, containerPresignEndpointFromEnv, createAssetsStorageClient, createContainerPresignStorage, createStorage, defaultKeystrokeAssetsPublicUrlBase, deleteWorkspaceObjects, ensureKeystrokeAssetsBucket, ensureStorageBucket, extractProjectArtifact, extractRouteManifestFromArtifact, isBucketAlreadyExistsError, isChatAttachmentStorageKey, isKeystrokeAssetsAvatarPublicUrl, isKeystrokeAssetsOrgLogoPublicUrl, isOrgLogoStorageKey, isSourceBlobHash, isStorageBucketNotFoundError, isStorageNotFoundError, isUserAvatarStorageKey, keystrokeAssetsAvatarKeyFromPublicUrl, keystrokeAssetsKeyFromPublicUrl, keystrokeAssetsOrgLogoKeyFromPublicUrl, keystrokeAssetsPublicUrlBase, loadProjectSourceFiles, mapInParallelBatches, mergeFilteredArtifact, mergeStoredRouteManifest, minioStoragePlugin, orgAgentBucketName, orgLogoStorageKey, orgStorageBucketName, packDistTree, packProjectArtifact, projectArtifactKey, projectSourceBlobKey, projectSourceManifestKey, publicKeystrokeAssetsObjectUrl, storageAdminConfigFromEnv, storageConfigFromEnv, syncAgentWorkspaceToBucket, uploadWorkspaceObjects, userAvatarStorageKey, workspaceKeysToDelete };\n\n//# sourceMappingURL=index.mjs.map"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"dist-QE1G9hAR.mjs","names":[],"sources":["../../../packages/storage/dist/pack-artifact-DVnIKrsg.mjs","../../../packages/storage/dist/index.mjs"],"sourcesContent":["import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\nimport { tmpdir } from \"node:os\";\nimport { ROUTE_MANIFEST_REL_PATH, parseStoredRouteManifest } from \"@keystrokehq/shared\";\n//#region src/pack-dir.ts\n/**\n* Pack a directory tree that contains a `dist/` folder into a gzip tarball\n* suitable for project-server extraction.\n*/\nfunction packDistTree(rootContainingDist) {\n\tconst tempDir = mkdtempSync(join(tmpdir(), \"keystroke-artifact-pack-\"));\n\tconst archivePath = join(tempDir, \"artifact.tgz\");\n\ttry {\n\t\tconst result = spawnSync(\"tar\", [\n\t\t\t\"-czf\",\n\t\t\tarchivePath,\n\t\t\t\"--exclude=._*\",\n\t\t\t\"--exclude=.DS_Store\",\n\t\t\t\"-C\",\n\t\t\trootContainingDist,\n\t\t\t\"dist\"\n\t\t], {\n\t\t\tencoding: \"utf8\",\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\tCOPYFILE_DISABLE: \"1\"\n\t\t\t}\n\t\t});\n\t\tif (result.status !== 0) throw new Error(result.stderr?.trim() || \"Failed to pack project artifact\");\n\t\treturn readFileSync(archivePath);\n\t} finally {\n\t\trmSync(tempDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/extract-artifact.ts\n/** Extract a packed project artifact tarball into `destDir` (creates `destDir/dist/`). */\nfunction extractProjectArtifact(archive, destDir) {\n\tconst tempDir = mkdtempSync(join(tmpdir(), \"keystroke-artifact-extract-\"));\n\tconst archivePath = join(tempDir, \"artifact.tgz\");\n\ttry {\n\t\twriteFileSync(archivePath, archive);\n\t\tconst result = spawnSync(\"tar\", [\n\t\t\t\"-xzf\",\n\t\t\tarchivePath,\n\t\t\t\"-C\",\n\t\t\tdestDir\n\t\t], {\n\t\t\tencoding: \"utf8\",\n\t\t\tenv: {\n\t\t\t\t...process.env,\n\t\t\t\tCOPYFILE_DISABLE: \"1\"\n\t\t\t}\n\t\t});\n\t\tif (result.status !== 0) throw new Error(result.stderr?.trim() || \"Failed to extract project artifact\");\n\t} finally {\n\t\trmSync(tempDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/merge-route-manifest.ts\nfunction moduleFileOf(entry) {\n\treturn \"moduleFile\" in entry && typeof entry.moduleFile === \"string\" ? entry.moduleFile : void 0;\n}\n/** Replace manifest rows for rebuilt modules while keeping untouched routes and metadata. */\nfunction mergeStoredRouteManifest(base, rebuiltEntries) {\n\tconst rebuiltModuleFiles = new Set(rebuiltEntries.map(moduleFileOf).filter((value) => Boolean(value)));\n\tconst keptEntries = base.entries.filter((entry) => {\n\t\tconst moduleFile = moduleFileOf(entry);\n\t\tif (!moduleFile) return true;\n\t\treturn !rebuiltModuleFiles.has(moduleFile);\n\t});\n\tconst filteredRebuilt = rebuiltEntries.filter((entry) => entry.kind !== \"health\");\n\treturn {\n\t\t...base,\n\t\tentries: [...keptEntries, ...filteredRebuilt]\n\t};\n}\n//#endregion\n//#region src/merge-filtered-artifact.ts\nasync function mergeFilteredArtifact(input) {\n\tconst mergeRoot = mkdtempSync(join(tmpdir(), \"keystroke-artifact-merge-\"));\n\ttry {\n\t\textractProjectArtifact(input.baseArchive, mergeRoot);\n\t\tconst manifestPath = join(mergeRoot, ROUTE_MANIFEST_REL_PATH);\n\t\tconst mergedManifest = mergeStoredRouteManifest(parseStoredRouteManifest(JSON.parse(readFileSync(manifestPath, \"utf8\"))), input.filtered.manifestEntries);\n\t\twriteFileSync(manifestPath, `${JSON.stringify(mergedManifest, null, 2)}\\n`);\n\t\tfor (const file of input.filtered.files) {\n\t\t\tconst destination = join(mergeRoot, \"dist\", file.relativePath);\n\t\t\tmkdirSync(dirname(destination), { recursive: true });\n\t\t\twriteFileSync(destination, file.contents);\n\t\t\tif (file.sourceMap) writeFileSync(`${destination}.map`, file.sourceMap);\n\t\t}\n\t\treturn packDistTree(mergeRoot);\n\t} finally {\n\t\trmSync(mergeRoot, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/pack-artifact.ts\n/** Pack `dist/` into a gzip tarball suitable for `/app` extraction in the project server image. */\nfunction packProjectArtifact(projectRoot) {\n\tif (!existsSync(join(projectRoot, \"dist\"))) throw new Error(\"dist/ not found — run keystroke build first\");\n\treturn packDistTree(projectRoot);\n}\n//#endregion\nexport { packDistTree as a, extractProjectArtifact as i, mergeFilteredArtifact as n, mergeStoredRouteManifest as r, packProjectArtifact as t };\n\n//# sourceMappingURL=pack-artifact-DVnIKrsg.mjs.map","import { a as packDistTree, i as extractProjectArtifact, n as mergeFilteredArtifact, r as mergeStoredRouteManifest, t as packProjectArtifact } from \"./pack-artifact-DVnIKrsg.mjs\";\nimport { CreateBucketCommand, DeleteBucketCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutBucketAclCommand, PutBucketPolicyCommand, PutObjectCommand, S3Client } from \"@aws-sdk/client-s3\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\nimport { tmpdir } from \"node:os\";\nimport { ROUTE_MANIFEST_REL_PATH } from \"@keystrokehq/shared\";\nimport { createHash } from \"node:crypto\";\n//#region src/config.ts\nfunction readEnv$1(env, ...keys) {\n\tfor (const key of keys) {\n\t\tconst value = env[key]?.trim();\n\t\tif (value) return value;\n\t}\n}\nfunction requireEnv(env, keys) {\n\tconst candidates = Array.isArray(keys) ? keys : [keys];\n\tconst value = readEnv$1(env, ...candidates);\n\tif (!value) throw new Error(`${candidates[0]} is required`);\n\treturn value;\n}\n/** Admin S3 credentials for storage plugins (bucket is per-org, not from env). */\nfunction storageAdminConfigFromEnv(env = process.env) {\n\tconst accessKeyId = requireEnv(env, [\"STORAGE_ACCESS_KEY_ID\", \"AWS_ACCESS_KEY_ID\"]);\n\tconst secretAccessKey = requireEnv(env, [\"STORAGE_SECRET_ACCESS_KEY\", \"AWS_SECRET_ACCESS_KEY\"]);\n\tconst endpoint = requireEnv(env, [\n\t\t\"STORAGE_ENDPOINT\",\n\t\t\"AWS_ENDPOINT_URL_S3\",\n\t\t\"AWS_S3_ENDPOINT\"\n\t]);\n\treturn {\n\t\tregion: readEnv$1(env, \"STORAGE_REGION\", \"AWS_REGION\") ?? \"us-east-1\",\n\t\taccessKeyId,\n\t\tsecretAccessKey,\n\t\tendpoint,\n\t\tforcePathStyle: env.STORAGE_FORCE_PATH_STYLE === void 0 ? true : env.STORAGE_FORCE_PATH_STYLE === \"true\"\n\t};\n}\n/** Full client config including bucket — for integration tests and explicit bucket callers. */\nfunction storageConfigFromEnv(env = process.env) {\n\tconst bucket = requireEnv(env, [\"STORAGE_BUCKET\", \"BUCKET_NAME\"]);\n\treturn {\n\t\t...storageAdminConfigFromEnv(env),\n\t\tbucket\n\t};\n}\n/** Endpoint for presigned URLs fetched inside project-server containers (e.g. `http://minio:9000`). */\nfunction containerPresignEndpointFromEnv(hostEndpoint, env = process.env) {\n\tconst override = readEnv$1(env, \"STORAGE_CONTAINER_ENDPOINT\");\n\tif (override) return override;\n\ttry {\n\t\tconst url = new URL(hostEndpoint);\n\t\tif (url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\") {\n\t\t\tconst port = url.port || (url.protocol === \"https:\" ? \"443\" : \"9000\");\n\t\t\treturn `${url.protocol}//minio:${port}`;\n\t\t}\n\t} catch {}\n\treturn hostEndpoint;\n}\n//#endregion\n//#region src/keys.ts\n/** Object key for a built project artifact tarball. */\nfunction projectArtifactKey(projectId, version) {\n\treturn `projects/${projectId}/artifacts/${version}.tgz`;\n}\n/**\n* Per-artifact source manifest (the deploy's file tree: path -> id + content\n* hash, plus resource refs). One per deploy.\n*/\nfunction projectSourceManifestKey(projectId, artifactId) {\n\treturn `projects/${projectId}/sources/${artifactId}/index.json`;\n}\nconst SHA256_HEX = /^[a-f0-9]{64}$/;\n/** True when `hash` is a lowercase hex sha256 digest (64 chars). */\nfunction isSourceBlobHash(hash) {\n\treturn SHA256_HEX.test(hash);\n}\n/**\n* Content-addressed key for a single source file's contents, deduped across all\n* of a project's deploys. `hash` is a lowercase hex sha256 of the file bytes.\n*/\nfunction projectSourceBlobKey(projectId, hash) {\n\tif (!isSourceBlobHash(hash)) throw new Error(\"Invalid source blob hash\");\n\treturn `projects/${projectId}/sources/blobs/${hash}`;\n}\nconst AVATAR_EXTENSION = /^[a-z0-9]+$/;\n/** Object key for a chat attachment in org-private storage. */\nfunction chatAttachmentStorageKey(projectId, id, ext) {\n\tconst normalizedExt = ext.replace(/^\\./, \"\").toLowerCase();\n\tif (!AVATAR_EXTENSION.test(normalizedExt)) throw new Error(\"Invalid chat attachment extension\");\n\treturn `chat-attachments/${projectId}/${id}.${normalizedExt}`;\n}\n/** True when `key` is a chat attachment owned by `projectId`. */\nfunction isChatAttachmentStorageKey(key, projectId) {\n\tconst prefix = `chat-attachments/${projectId}/`;\n\tif (!key.startsWith(prefix)) return false;\n\tconst remainder = key.slice(prefix.length);\n\treturn remainder.length > 0 && !remainder.includes(\"/\");\n}\n/** Object key for a user's custom profile avatar in the shared keystroke-users bucket. */\nfunction userAvatarStorageKey(userId, extension) {\n\tconst ext = extension.replace(/^\\./, \"\").toLowerCase();\n\tif (!AVATAR_EXTENSION.test(ext)) throw new Error(\"Invalid avatar extension\");\n\treturn `avatars/${userId}/avatar.${ext}`;\n}\n/** True when `key` is the canonical avatar object for `userId`. */\nfunction isUserAvatarStorageKey(key, userId) {\n\tconst prefix = `avatars/${userId}/avatar.`;\n\tif (!key.startsWith(prefix)) return false;\n\tconst ext = key.slice(prefix.length);\n\treturn AVATAR_EXTENSION.test(ext);\n}\n/** Object key for an org logo in the shared keystroke-assets bucket. */\nfunction orgLogoStorageKey(organizationId, variant, extension) {\n\tconst ext = extension.replace(/^\\./, \"\").toLowerCase();\n\tif (!AVATAR_EXTENSION.test(ext)) throw new Error(\"Invalid org logo extension\");\n\treturn `org-logos/${organizationId}/logo-${variant}.${ext}`;\n}\n/** True when `key` is the canonical logo object for `organizationId` and `variant`. */\nfunction isOrgLogoStorageKey(key, organizationId, variant) {\n\tconst prefix = `org-logos/${organizationId}/logo-${variant}.`;\n\tif (!key.startsWith(prefix)) return false;\n\tconst ext = key.slice(prefix.length);\n\treturn AVATAR_EXTENSION.test(ext);\n}\n//#endregion\n//#region src/map-in-batches.ts\n/** Default concurrency for parallel blob downloads and file writes. */\nconst DEFAULT_PARALLEL_BATCH_SIZE = 8;\n/** Run `fn` over `items` in parallel batches of `batchSize`. */\nasync function mapInParallelBatches(items, batchSize, fn) {\n\tif (batchSize < 1) throw new Error(\"batchSize must be at least 1\");\n\tconst results = [];\n\tfor (let index = 0; index < items.length; index += batchSize) {\n\t\tconst batch = items.slice(index, index + batchSize);\n\t\tresults.push(...await Promise.all(batch.map(fn)));\n\t}\n\treturn results;\n}\n//#endregion\n//#region src/load-project-source-files.ts\n/** Matches deploy-time source snapshot limits in @keystrokehq/build walk-project. */\nconst MAX_ACTIVE_SOURCE_DOWNLOAD_BYTES = 8 * 1024 * 1024;\nasync function loadProjectSourceFiles(storage, projectId, manifest, options = {}) {\n\tconst maxTotalBytes = options.maxTotalBytes ?? 8388608;\n\tconst files = [];\n\tlet totalBytes = 0;\n\tfor (let index = 0; index < manifest.files.length; index += 8) {\n\t\tconst batch = manifest.files.slice(index, index + 8);\n\t\tconst batchResults = await Promise.all(batch.map(async (file) => {\n\t\t\tconst bytes = await storage.getObject(projectSourceBlobKey(projectId, file.hash));\n\t\t\tconst contents = new TextDecoder().decode(bytes);\n\t\t\treturn {\n\t\t\t\tpath: file.path,\n\t\t\t\tcontents,\n\t\t\t\tbyteLength: Buffer.byteLength(contents, \"utf8\")\n\t\t\t};\n\t\t}));\n\t\tfor (const result of batchResults) {\n\t\t\ttotalBytes += result.byteLength;\n\t\t\tif (totalBytes > maxTotalBytes) throw new Error(\"Active source snapshot exceeds download size limit\");\n\t\t\tfiles.push({\n\t\t\t\tpath: result.path,\n\t\t\t\tcontents: result.contents\n\t\t\t});\n\t\t}\n\t}\n\treturn files;\n}\n//#endregion\n//#region src/create-storage.ts\nconst DEFAULT_PRESIGN_TTL_SECONDS = 900;\nfunction createStorage(config) {\n\tconst client = new S3Client(toClientConfig(config));\n\treturn {\n\t\tasync putObject(input) {\n\t\t\tawait client.send(new PutObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: input.key,\n\t\t\t\tBody: input.body,\n\t\t\t\tContentType: input.contentType\n\t\t\t}));\n\t\t},\n\t\tasync getObject(key) {\n\t\t\tconst response = await client.send(new GetObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: key\n\t\t\t}));\n\t\t\tif (!response.Body) throw new Error(`Object body missing for key ${key}`);\n\t\t\treturn response.Body.transformToByteArray();\n\t\t},\n\t\tasync headObject(key) {\n\t\t\ttry {\n\t\t\t\treturn { contentLength: (await client.send(new HeadObjectCommand({\n\t\t\t\t\tBucket: config.bucket,\n\t\t\t\t\tKey: key\n\t\t\t\t}))).ContentLength ?? 0 };\n\t\t\t} catch (error) {\n\t\t\t\tif (isNotFoundError(error)) return;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tasync presignGet(input) {\n\t\t\treturn getSignedUrl(client, new GetObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: input.key\n\t\t\t}), { expiresIn: input.expiresInSeconds ?? DEFAULT_PRESIGN_TTL_SECONDS });\n\t\t},\n\t\tasync presignPut(input) {\n\t\t\treturn getSignedUrl(client, new PutObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: input.key,\n\t\t\t\tContentType: input.contentType ?? \"application/gzip\"\n\t\t\t}), { expiresIn: input.expiresInSeconds ?? DEFAULT_PRESIGN_TTL_SECONDS });\n\t\t},\n\t\tasync deleteObject(key) {\n\t\t\tawait client.send(new DeleteObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: key\n\t\t\t}));\n\t\t},\n\t\tasync listObjects(prefix) {\n\t\t\tconst keys = [];\n\t\t\tlet continuationToken;\n\t\t\tdo {\n\t\t\t\tconst response = await client.send(new ListObjectsV2Command({\n\t\t\t\t\tBucket: config.bucket,\n\t\t\t\t\tPrefix: prefix,\n\t\t\t\t\tContinuationToken: continuationToken\n\t\t\t\t}));\n\t\t\t\tfor (const object of response.Contents ?? []) if (object.Key) keys.push(object.Key);\n\t\t\t\tcontinuationToken = response.IsTruncated ? response.NextContinuationToken : void 0;\n\t\t\t} while (continuationToken);\n\t\t\treturn keys;\n\t\t}\n\t};\n}\n/** Presign URLs for project-server containers using `STORAGE_CONTAINER_ENDPOINT` when set. */\nfunction createContainerPresignStorage(config, env = process.env) {\n\treturn createStorage({\n\t\t...config,\n\t\tendpoint: containerPresignEndpointFromEnv(config.endpoint, env)\n\t});\n}\nfunction toClientConfig(config) {\n\treturn {\n\t\tregion: config.region,\n\t\tcredentials: {\n\t\t\taccessKeyId: config.accessKeyId,\n\t\t\tsecretAccessKey: config.secretAccessKey\n\t\t},\n\t\tendpoint: config.endpoint,\n\t\tforcePathStyle: config.forcePathStyle\n\t};\n}\nfunction isNotFoundError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst name = \"name\" in error ? String(error.name) : \"\";\n\tconst status = \"$metadata\" in error ? error.$metadata : void 0;\n\treturn name === \"NotFound\" || name === \"NoSuchKey\" || status?.httpStatusCode === 404;\n}\n//#endregion\n//#region src/extract-route-manifest.ts\nvar RouteManifestNotFoundError = class extends Error {\n\tconstructor(message = `Route manifest missing in artifact (${ROUTE_MANIFEST_REL_PATH})`) {\n\t\tsuper(message);\n\t\tthis.name = \"RouteManifestNotFoundError\";\n\t}\n};\n/** Read `.keystroke/route-manifest.json` from a packed project artifact tarball. */\nfunction extractRouteManifestFromArtifact(archive) {\n\tconst tempDir = mkdtempSync(join(tmpdir(), \"keystroke-artifact-\"));\n\tconst archivePath = join(tempDir, \"artifact.tgz\");\n\ttry {\n\t\twriteFileSync(archivePath, archive);\n\t\tif (spawnSync(\"tar\", [\n\t\t\t\"-xzf\",\n\t\t\tarchivePath,\n\t\t\t\"-C\",\n\t\t\ttempDir,\n\t\t\tROUTE_MANIFEST_REL_PATH\n\t\t], { encoding: \"utf8\" }).status !== 0) throw new RouteManifestNotFoundError();\n\t\tconst raw = readFileSync(join(tempDir, ROUTE_MANIFEST_REL_PATH), \"utf8\");\n\t\treturn JSON.parse(raw);\n\t} catch (error) {\n\t\tif (error instanceof RouteManifestNotFoundError) throw error;\n\t\tthrow new RouteManifestNotFoundError(error instanceof Error ? error.message : \"Failed to extract route manifest\");\n\t} finally {\n\t\trmSync(tempDir, {\n\t\t\trecursive: true,\n\t\t\tforce: true\n\t\t});\n\t}\n}\n//#endregion\n//#region src/s3-errors.ts\nfunction isBucketAlreadyExistsError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst name = \"name\" in error ? String(error.name) : \"\";\n\tconst code = \"Code\" in error ? String(error.Code) : \"\";\n\treturn name === \"BucketAlreadyOwnedByYou\" || code === \"BucketAlreadyOwnedByYou\" || name === \"BucketAlreadyExists\" || code === \"BucketAlreadyExists\";\n}\nfunction isStorageNotFoundError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst record = error;\n\tconst name = typeof record.name === \"string\" ? record.name : \"\";\n\tconst code = typeof record.Code === \"string\" ? record.Code : \"\";\n\tconst status = typeof record.$metadata === \"object\" && record.$metadata !== null ? record.$metadata.httpStatusCode : void 0;\n\treturn name === \"NoSuchKey\" || code === \"NoSuchKey\" || code === \"NotFound\" || status === 404;\n}\nfunction isStorageBucketNotFoundError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst record = error;\n\tconst name = typeof record.name === \"string\" ? record.name : \"\";\n\tconst code = typeof record.Code === \"string\" ? record.Code : \"\";\n\tconst status = typeof record.$metadata === \"object\" && record.$metadata !== null ? record.$metadata.httpStatusCode : void 0;\n\treturn name === \"NoSuchBucket\" || code === \"NoSuchBucket\" || name === \"NotFound\" || status === 404;\n}\n//#endregion\n//#region src/asset-storage.ts\n/** Shared bucket for cross-org public assets (avatars, org sidebar logos). */\nconst KEYSTROKE_ASSETS_BUCKET = \"keystroke-assets\";\n/** Env var for the browser-facing origin of public asset objects (no trailing slash). */\nconst KEYSTROKE_ASSETS_PUBLIC_URL_BASE_ENV = \"KEYSTROKE_ASSETS_PUBLIC_URL_BASE\";\nconst KEYSTROKE_ASSETS_AVATAR_PREFIX = \"avatars/\";\nconst KEYSTROKE_ASSETS_ORG_LOGO_PREFIX = \"org-logos/\";\nfunction readEnv(env, key) {\n\treturn env[key]?.trim() || void 0;\n}\n/** Default path-style base when `KEYSTROKE_ASSETS_PUBLIC_URL_BASE` is unset (local MinIO). */\nfunction defaultKeystrokeAssetsPublicUrlBase(env = process.env) {\n\treturn `${storageAdminConfigFromEnv(env).endpoint.replace(/\\/+$/, \"\")}/${KEYSTROKE_ASSETS_BUCKET}`;\n}\n/** Public URL prefix for asset objects — configured base or local path-style default. */\nfunction keystrokeAssetsPublicUrlBase(env = process.env) {\n\tconst configured = readEnv(env, KEYSTROKE_ASSETS_PUBLIC_URL_BASE_ENV);\n\tif (configured) return configured.replace(/\\/+$/, \"\");\n\treturn defaultKeystrokeAssetsPublicUrlBase(env);\n}\nfunction keystrokeAssetsPublicUrlPrefixes(env = process.env) {\n\tconst prefixes = [keystrokeAssetsPublicUrlBase(env)];\n\tif (readEnv(env, \"KEYSTROKE_ASSETS_PUBLIC_URL_BASE\")) prefixes.push(defaultKeystrokeAssetsPublicUrlBase(env));\n\treturn [...new Set(prefixes)];\n}\nfunction createAssetsStorageClient(env = process.env) {\n\treturn createStorage({\n\t\t...storageAdminConfigFromEnv(env),\n\t\tbucket: KEYSTROKE_ASSETS_BUCKET\n\t});\n}\n/** Stable public URL for an object in the keystroke-assets bucket. */\nfunction publicKeystrokeAssetsObjectUrl(key, env = process.env) {\n\treturn `${keystrokeAssetsPublicUrlBase(env)}/${key}`;\n}\n/** Extract the object key from a public keystroke-assets URL when it matches `requiredPrefix`. */\nfunction keystrokeAssetsKeyFromPublicUrl(url, requiredPrefix, env = process.env) {\n\tfor (const prefix of keystrokeAssetsPublicUrlPrefixes(env)) {\n\t\tconst normalizedPrefix = `${prefix.replace(/\\/+$/, \"\")}/`;\n\t\tif (!url.startsWith(normalizedPrefix)) continue;\n\t\tconst key = decodeURIComponent(url.slice(normalizedPrefix.length).split(\"?\")[0] ?? \"\");\n\t\tif (key.startsWith(requiredPrefix)) return key;\n\t}\n\treturn null;\n}\nfunction isKeystrokeAssetsAvatarPublicUrl(url, env = process.env) {\n\treturn keystrokeAssetsKeyFromPublicUrl(url, KEYSTROKE_ASSETS_AVATAR_PREFIX, env) !== null;\n}\nfunction keystrokeAssetsAvatarKeyFromPublicUrl(url, env = process.env) {\n\treturn keystrokeAssetsKeyFromPublicUrl(url, KEYSTROKE_ASSETS_AVATAR_PREFIX, env);\n}\nfunction isKeystrokeAssetsOrgLogoPublicUrl(url, env = process.env) {\n\treturn keystrokeAssetsKeyFromPublicUrl(url, KEYSTROKE_ASSETS_ORG_LOGO_PREFIX, env) !== null;\n}\nfunction keystrokeAssetsOrgLogoKeyFromPublicUrl(url, env = process.env) {\n\treturn keystrokeAssetsKeyFromPublicUrl(url, KEYSTROKE_ASSETS_ORG_LOGO_PREFIX, env);\n}\nasync function ensureKeystrokeAssetsBucket(env = process.env) {\n\tconst adminConfig = storageAdminConfigFromEnv(env);\n\tconst adminClient = new S3Client({\n\t\tregion: adminConfig.region,\n\t\tcredentials: {\n\t\t\taccessKeyId: adminConfig.accessKeyId,\n\t\t\tsecretAccessKey: adminConfig.secretAccessKey\n\t\t},\n\t\tendpoint: adminConfig.endpoint,\n\t\tforcePathStyle: adminConfig.forcePathStyle\n\t});\n\tawait createAssetsBucketIfNeeded(adminClient, KEYSTROKE_ASSETS_BUCKET);\n\tawait applyPublicAssetsBucketAcl(adminClient, KEYSTROKE_ASSETS_BUCKET);\n\tawait applyPublicAssetsBucketPolicy(adminClient, KEYSTROKE_ASSETS_BUCKET);\n}\nasync function createAssetsBucketIfNeeded(adminClient, bucket) {\n\ttry {\n\t\tawait adminClient.send(new CreateBucketCommand({\n\t\t\tBucket: bucket,\n\t\t\tACL: \"public-read\"\n\t\t}));\n\t\treturn;\n\t} catch (error) {\n\t\tif (isBucketAlreadyExistsError(error)) return;\n\t}\n\ttry {\n\t\tawait adminClient.send(new CreateBucketCommand({ Bucket: bucket }));\n\t} catch (error) {\n\t\tif (!isBucketAlreadyExistsError(error)) throw error;\n\t}\n}\nasync function applyPublicAssetsBucketAcl(adminClient, bucket) {\n\ttry {\n\t\tawait adminClient.send(new PutBucketAclCommand({\n\t\t\tBucket: bucket,\n\t\t\tACL: \"public-read\"\n\t\t}));\n\t} catch (error) {\n\t\tif (!isUnsupportedStorageFeatureError(error)) console.warn(\"[storage] PutBucketAcl failed (continuing):\", error);\n\t}\n}\nasync function applyPublicAssetsBucketPolicy(adminClient, bucket) {\n\ttry {\n\t\tawait adminClient.send(new PutBucketPolicyCommand({\n\t\t\tBucket: bucket,\n\t\t\tPolicy: JSON.stringify({\n\t\t\t\tVersion: \"2012-10-17\",\n\t\t\t\tStatement: [{\n\t\t\t\t\tEffect: \"Allow\",\n\t\t\t\t\tPrincipal: \"*\",\n\t\t\t\t\tAction: [\"s3:GetObject\"],\n\t\t\t\t\tResource: [`arn:aws:s3:::${bucket}/${KEYSTROKE_ASSETS_AVATAR_PREFIX}*`, `arn:aws:s3:::${bucket}/${KEYSTROKE_ASSETS_ORG_LOGO_PREFIX}*`]\n\t\t\t\t}]\n\t\t\t})\n\t\t}));\n\t} catch (error) {\n\t\tif (!isUnsupportedStorageFeatureError(error)) console.warn(\"[storage] PutBucketPolicy failed (continuing):\", error);\n\t}\n}\nfunction isUnsupportedStorageFeatureError(error) {\n\tif (!error || typeof error !== \"object\") return false;\n\tconst name = \"name\" in error ? String(error.name) : \"\";\n\tconst code = \"Code\" in error ? String(error.Code) : \"\";\n\treturn name === \"NotImplemented\" || code === \"NotImplemented\" || code === \"NotSupported\";\n}\n//#endregion\n//#region src/provision/names.ts\nconst DEFAULT_BUCKET_NAME_PREFIX = \"ks\";\nconst S3_BUCKET_NAME_MAX = 63;\n/** Deterministic bucket segment; keeps short test ids readable, hashes UUID-length ids. */\nfunction bucketIdSegment(id, hashLength = 10) {\n\tif (id.length <= 24 && !/^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(id)) return id;\n\treturn createHash(\"sha256\").update(id).digest(\"hex\").slice(0, hashLength);\n}\nfunction assertBucketName(name) {\n\tif (name.length > S3_BUCKET_NAME_MAX) throw new Error(`bucket name exceeds ${S3_BUCKET_NAME_MAX} chars (${name.length}): ${name}`);\n\treturn name;\n}\nfunction orgStorageBucketName(input, prefix = DEFAULT_BUCKET_NAME_PREFIX) {\n\treturn assertBucketName(`${prefix.trim().replace(/-+$/g, \"\")}-${input.organizationId.toLowerCase()}`);\n}\nfunction orgAgentBucketName(input) {\n\tconst orgBucket = input.orgBucket ?? (input.organizationId ? orgStorageBucketName({ organizationId: input.organizationId }) : void 0);\n\tif (!orgBucket) throw new Error(\"orgAgentBucketName requires organizationId or orgBucket\");\n\treturn assertBucketName(`${orgBucket}-${bucketIdSegment(input.agentId)}`);\n}\n//#endregion\n//#region src/workspace/sync.ts\nconst DEFAULT_UPLOAD_CONCURRENCY = 8;\nfunction walkFiles(root) {\n\tconst files = [];\n\tconst stack = [root];\n\twhile (stack.length > 0) {\n\t\tconst current = stack.pop();\n\t\tfor (const entry of readdirSync(current, { withFileTypes: true })) {\n\t\t\tconst full = join(current, entry.name);\n\t\t\tif (entry.isDirectory()) stack.push(full);\n\t\t\telse if (entry.isFile()) files.push(full);\n\t\t}\n\t}\n\treturn files;\n}\nfunction collectWorkspaceObjects(workspaceRoot) {\n\treturn walkFiles(workspaceRoot).map((file) => ({\n\t\tkey: relative(workspaceRoot, file).split(\"\\\\\").join(\"/\"),\n\t\tbody: readFileSync(file)\n\t}));\n}\n/** Keys present in object storage but absent from the local workspace root. */\nfunction workspaceKeysToDelete(remoteKeys, localKeys) {\n\treturn remoteKeys.filter((key) => !localKeys.has(key));\n}\nfunction s3Client(config) {\n\treturn new S3Client({\n\t\tregion: config.region,\n\t\tendpoint: config.endpoint,\n\t\tforcePathStyle: config.forcePathStyle,\n\t\tcredentials: {\n\t\t\taccessKeyId: config.accessKeyId,\n\t\t\tsecretAccessKey: config.secretAccessKey\n\t\t}\n\t});\n}\n/** Create the bucket named in `config` when missing (idempotent for races). */\nasync function ensureStorageBucket(config) {\n\tconst client = s3Client(config);\n\ttry {\n\t\tawait client.send(new CreateBucketCommand({ Bucket: config.bucket }));\n\t} catch (error) {\n\t\tif (!isBucketAlreadyExistsError(error)) throw error;\n\t}\n}\nasync function uploadWorkspaceObjects(config, objects, concurrency = DEFAULT_UPLOAD_CONCURRENCY) {\n\tif (objects.length === 0) return;\n\tconst client = s3Client(config);\n\tlet index = 0;\n\tasync function worker() {\n\t\twhile (index < objects.length) {\n\t\t\tconst current = objects[index++];\n\t\t\tawait client.send(new PutObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: current.key,\n\t\t\t\tBody: current.body\n\t\t\t}));\n\t\t}\n\t}\n\tconst workers = Array.from({ length: Math.min(concurrency, objects.length) }, () => worker());\n\tawait Promise.all(workers);\n}\nasync function deleteWorkspaceObjects(config, keys, concurrency = DEFAULT_UPLOAD_CONCURRENCY) {\n\tif (keys.length === 0) return;\n\tconst client = s3Client(config);\n\tlet index = 0;\n\tasync function worker() {\n\t\twhile (index < keys.length) {\n\t\t\tconst key = keys[index++];\n\t\t\tawait client.send(new DeleteObjectCommand({\n\t\t\t\tBucket: config.bucket,\n\t\t\t\tKey: key\n\t\t\t}));\n\t\t}\n\t}\n\tconst workers = Array.from({ length: Math.min(concurrency, keys.length) }, () => worker());\n\tawait Promise.all(workers);\n}\n/** Mirror the host agent workspace directory to the per-agent bucket (upsert + delete stale keys). */\nasync function syncAgentWorkspaceToBucket(input) {\n\tconst bucket = orgAgentBucketName({\n\t\torgBucket: input.orgBucket,\n\t\tagentId: input.agentId\n\t});\n\tconst config = {\n\t\t...input.admin,\n\t\tbucket\n\t};\n\tawait ensureStorageBucket(config);\n\tconst objects = collectWorkspaceObjects(input.agentRoot);\n\tconst localKeys = new Set(objects.map((object) => object.key));\n\tawait deleteWorkspaceObjects(config, workspaceKeysToDelete(await createStorage(config).listObjects(\"\"), localKeys));\n\tawait uploadWorkspaceObjects(config, objects);\n}\n//#endregion\n//#region src/provision/minio.ts\nfunction minioStoragePlugin(options = {}) {\n\tconst adminConfig = storageAdminConfigFromEnv(options.env ?? process.env);\n\tconst adminClient = new S3Client({\n\t\tregion: adminConfig.region,\n\t\tcredentials: {\n\t\t\taccessKeyId: adminConfig.accessKeyId,\n\t\t\tsecretAccessKey: adminConfig.secretAccessKey\n\t\t},\n\t\tendpoint: adminConfig.endpoint,\n\t\tforcePathStyle: adminConfig.forcePathStyle\n\t});\n\treturn {\n\t\tasync provisionOrganization(input) {\n\t\t\tconst bucket = orgStorageBucketName(input, options.bucketNamePrefix);\n\t\t\ttry {\n\t\t\t\tawait adminClient.send(new CreateBucketCommand({ Bucket: bucket }));\n\t\t\t} catch (error) {\n\t\t\t\tif (!isBucketAlreadyExistsError(error)) throw error;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tbucket,\n\t\t\t\tendpoint: adminConfig.endpoint,\n\t\t\t\taccessKeyId: adminConfig.accessKeyId,\n\t\t\t\tsecretAccessKey: adminConfig.secretAccessKey,\n\t\t\t\tregion: adminConfig.region,\n\t\t\t\tforcePathStyle: adminConfig.forcePathStyle\n\t\t\t};\n\t\t},\n\t\tasync deprovisionOrganization(result) {\n\t\t\tconst client = new S3Client({\n\t\t\t\tregion: result.region ?? adminConfig.region,\n\t\t\t\tcredentials: {\n\t\t\t\t\taccessKeyId: result.accessKeyId,\n\t\t\t\t\tsecretAccessKey: result.secretAccessKey\n\t\t\t\t},\n\t\t\t\tendpoint: result.endpoint,\n\t\t\t\tforcePathStyle: result.forcePathStyle ?? true\n\t\t\t});\n\t\t\tif (((await client.send(new ListObjectsV2Command({\n\t\t\t\tBucket: result.bucket,\n\t\t\t\tMaxKeys: 1\n\t\t\t}))).KeyCount ?? 0) > 0) throw new Error(`Refusing to delete non-empty storage bucket ${result.bucket}`);\n\t\t\tawait client.send(new DeleteBucketCommand({ Bucket: result.bucket }));\n\t\t}\n\t};\n}\n//#endregion\nexport { DEFAULT_PARALLEL_BATCH_SIZE, KEYSTROKE_ASSETS_AVATAR_PREFIX, KEYSTROKE_ASSETS_BUCKET, KEYSTROKE_ASSETS_ORG_LOGO_PREFIX, KEYSTROKE_ASSETS_PUBLIC_URL_BASE_ENV, MAX_ACTIVE_SOURCE_DOWNLOAD_BYTES, RouteManifestNotFoundError, bucketIdSegment, chatAttachmentStorageKey, collectWorkspaceObjects, containerPresignEndpointFromEnv, createAssetsStorageClient, createContainerPresignStorage, createStorage, defaultKeystrokeAssetsPublicUrlBase, deleteWorkspaceObjects, ensureKeystrokeAssetsBucket, ensureStorageBucket, extractProjectArtifact, extractRouteManifestFromArtifact, isBucketAlreadyExistsError, isChatAttachmentStorageKey, isKeystrokeAssetsAvatarPublicUrl, isKeystrokeAssetsOrgLogoPublicUrl, isOrgLogoStorageKey, isSourceBlobHash, isStorageBucketNotFoundError, isStorageNotFoundError, isUserAvatarStorageKey, keystrokeAssetsAvatarKeyFromPublicUrl, keystrokeAssetsKeyFromPublicUrl, keystrokeAssetsOrgLogoKeyFromPublicUrl, keystrokeAssetsPublicUrlBase, loadProjectSourceFiles, mapInParallelBatches, mergeFilteredArtifact, mergeStoredRouteManifest, minioStoragePlugin, orgAgentBucketName, orgLogoStorageKey, orgStorageBucketName, packDistTree, packProjectArtifact, projectArtifactKey, projectSourceBlobKey, projectSourceManifestKey, publicKeystrokeAssetsObjectUrl, storageAdminConfigFromEnv, storageConfigFromEnv, syncAgentWorkspaceToBucket, uploadWorkspaceObjects, userAvatarStorageKey, workspaceKeysToDelete };\n\n//# sourceMappingURL=index.mjs.map"],"mappings":"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"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { $ as
|
|
3
|
-
import { a as installPlaygroundDependencies, c as createCliConfig, d as getEffectiveApiTarget, f as getPlatformUrl, g as resolvePlatformUrlForWebUrl, i as installDependencies$1, l as getCliConfigDir, m as DEFAULT_PLATFORM_URL, n as buildPlaygroundWorkspace, o as resolvePackageManager, p as getWebUrl, s as resolveCliRoot, t as readCliVersion, u as getConfigDir } from "./version-
|
|
4
|
-
import { n as mergeFilteredArtifact, r as packProjectArtifact, t as mapInParallelBatches } from "./dist-
|
|
2
|
+
import { $ as HealthResponseSchema, $t as StartKeystrokeConnectionResultSchema, A as CreateCustomAppRequestSchema, An as WorkflowSummaryDetailResponseSchema, At as PresignChatAttachmentResponseSchema, B as CredentialConsumerListQuerySchema, Bn as detectProjectPackageManagerFromSnapshot, Bt as ProjectSettingsResponseSchema, C as ConnectAuthorizeUrlResponseSchema, Cn as UserAvatarPatchSchema, Ct as OpenApiDiscoverResponseSchema, D as CreateCredentialInstanceBodySchema, Dn as WorkflowRunDetailResponseSchema, Dt as PROJECT_REACHABILITY_REQUEST_TIMEOUT_MS, E as CreateApiKeyResponseSchema, En as UserPreferencesSchema, Et as PROJECT_PULL_STATE_RELATIVE_PATH, F as CreateProjectRequestSchema, Fn as WorkspaceTriggerOverviewSchema, Ft as PresignUserAvatarRequestSchema, G as DeclineOrganizationInvitationResponseSchema, Gn as parseAppSlug, Gt as QueuedAgentPromptResponseSchema, H as CredentialInstanceListResponseSchema, Hn as listenPortFromPublicUrl, Ht as PromptInputSchema, I as CreateProjectResponseSchema, In as WorkspaceTriggerRunListResponseSchema, It as PresignUserAvatarResponseSchema, J as ErrorResponseSchema, Jn as resolveConnectAppSlug, Jt as RecentResourceListResponseSchema, K as DownloadActiveProjectArtifactResponseSchema, Kn as parseErrorResponse, Kt as QueuedRunResponseSchema, L as CredentialAssignmentListQuerySchema, Ln as buildConnectDeeplink, Lt as ProjectPullStateSchema, M as CreateOrganizationRequestSchema, Mn as WorkspaceTriggerDetailSchema, Mt as PresignOrgLogoResponseSchema, N as CreateOrganizationResponseSchema, Nn as WorkspaceTriggerFileSchema, Nt as PresignProjectSourceRequestSchema, O as CreateCredentialsRequestSchema, On as WorkflowRunHooksResponseSchema, Ot as PollRunResponseSchema, P as CreateProjectArtifactResponseSchema, Pn as WorkspaceTriggerListResponseSchema, Pt as PresignProjectSourceResponseSchema, Q as GraphqlDiscoverResponseSchema, Qt as StartKeystrokeConnectionInputSchema, R as CredentialAssignmentListResponseSchema, Rt as ProjectReachabilityResponseSchema, S as CompleteProjectArtifactResponseSchema, Sn as UpsertGatewayAttachmentBodySchema, St as McpDiscoverResponseSchema, T as CreateApiKeyRequestSchema, Tn as UserPreferencesPatchSchema, Tt as OrganizationSidebarBrandingSchema, U as CredentialInstanceRecordSchema, Ut as PromptResponseSchema, V as CredentialConsumerListResponseSchema, Vn as isAcceptableInstallExit, Vt as ProjectSlugAvailabilityResponseSchema, X as GetCredentialResponseSchema, Xn as slugifyAppName, Xt as SkillSummaryListResponseSchema, Y as GatewayAttachmentRecordSchema, Yn as resolvePublicPlatformOrigin, Yt as SkillSummaryDetailResponseSchema, Z as GetCustomAppResponseSchema, Zt as SlugAvailabilityResponseSchema, _ as ChannelAccountListResponseSchema, _n as UpdateProjectMemberResponseSchema, _t as ListProjectDeploymentsResponseSchema, a as AgentSessionDetailResponseSchema, an as SubmitTeamRequestRequestSchema, at as InviteOrganizationMembersResponseSchema, b as ChannelDirectoryListResponseSchema, bn as UploadProjectSourceManifestRequestSchema, bt as ListProjectMetricsResponseSchema, c as AgentSummaryListResponseSchema, cn as TriggerRunDetailResponseSchema, d as AssignCredentialBodySchema, dn as UpdateCredentialInstanceBodySchema, dt as ListApiKeysResponseSchema, en as StartMcpOAuthConnectionInputSchema, et as HistoryRunCancelResponseSchema, f as BindChannelBodySchema, fn as UpdateCredentialRequestSchema, ft as ListAppsResponseSchema, g as CatalogAppsPageResponseSchema, gn as UpdateProjectMemberRequestSchema, gt as ListOrganizationsResponseSchema, h as CatalogAppDetailResponseSchema, hn as UpdateOrganizationRequestSchema, ht as ListOrganizationMembersResponseSchema, i as AgentSessionChatStateResponseSchema, in as SubmitMarketingContactRequestSchema, it as InviteOrganizationMembersRequestSchema, j as CreateCustomAppResponseSchema, jn as WorkflowSummaryListResponseSchema, jt as PresignOrgLogoRequestSchema, k as CreateCredentialsResponseSchema, kn as WorkflowRunListResponseSchema, kt as PresignChatAttachmentRequestSchema, l as AgentTriggerSummaryListResponseSchema, ln as TriggerRunListResponseSchema, lt as ListAgentMemoryFilesResponseSchema, m as CatalogActionsPageResponseSchema, mn as UpdateOrganizationMemberResponseSchema, mt as ListOrganizationInvitationsResponseSchema, n as AcceptOrganizationInvitationResponseSchema, nn as StartOAuthConnectionInputSchema, nt as HistoryRunListQuerySchema, o as AgentSessionListResponseSchema, on as TriggerDetailResponseSchema, ot as InviteProjectMembersRequestSchema, p as CatalogActionDetailResponseSchema, pn as UpdateOrganizationMemberRequestSchema, pt as ListCredentialsResponseSchema, q as DownloadActiveProjectSourceResponseSchema, r as ActiveOrganizationResponseSchema, rn as StartOAuthConnectionResultSchema, rt as HistoryRunListResponseSchema, s as AgentSummaryDetailResponseSchema, sn as TriggerListResponseSchema, st as InviteProjectMembersResponseSchema, t as ACTIVE_ORG_HEADER, tn as StartMcpOAuthConnectionResultSchema, tt as HistoryRunDetailResponseSchema, u as AppSlugAvailabilityResponseSchema, un as UpdateChannelBindingBodySchema, ut as ListAgentWorkspaceFilesResponseSchema, v as ChannelConnectionListResponseSchema, vn as UpdateProjectRequestSchema, vt as ListProjectFilesResponseSchema, w as ConnectProvidersResponseSchema, wn as UserAvatarSchema, wt as OrganizationSidebarBrandingPatchSchema, x as ChannelPlatformSchema, xn as UploadProjectSourceResponseSchema, xt as ListProjectsResponseSchema, y as ChannelConnectionSchema, yn as UpdateProjectSettingsRequestSchema, yt as ListProjectMembersResponseSchema, z as CredentialAssignmentRecordSchema, zn as deriveCustomAppDisplay, zt as ProjectResponseSchema } from "./dist-DmqYCJqU.mjs";
|
|
3
|
+
import { a as installPlaygroundDependencies, c as createCliConfig, d as getEffectiveApiTarget, f as getPlatformUrl, g as resolvePlatformUrlForWebUrl, i as installDependencies$1, l as getCliConfigDir, m as DEFAULT_PLATFORM_URL, n as buildPlaygroundWorkspace, o as resolvePackageManager, p as getWebUrl, s as resolveCliRoot, t as readCliVersion, u as getConfigDir } from "./version-BudDbxko.mjs";
|
|
4
|
+
import { n as mergeFilteredArtifact, r as packProjectArtifact, t as mapInParallelBatches } from "./dist-QE1G9hAR.mjs";
|
|
5
5
|
import { createRequire } from "node:module";
|
|
6
6
|
import { Command } from "commander";
|
|
7
7
|
import { platform } from "node:os";
|
|
@@ -5375,25 +5375,117 @@ function collectValues$1(value, previous) {
|
|
|
5375
5375
|
}
|
|
5376
5376
|
//#endregion
|
|
5377
5377
|
//#region src/commands/app/run-app-create.ts
|
|
5378
|
-
async function runAppCreate(client, input) {
|
|
5378
|
+
async function runAppCreate(client, input, options) {
|
|
5379
|
+
if (options?.preview) return {
|
|
5380
|
+
preview: true,
|
|
5381
|
+
request: input,
|
|
5382
|
+
slug: await client.apps.checkSlug(input.slug)
|
|
5383
|
+
};
|
|
5379
5384
|
return client.apps.create(input);
|
|
5380
5385
|
}
|
|
5381
5386
|
//#endregion
|
|
5387
|
+
//#region src/commands/app/run-app-create-from-url.ts
|
|
5388
|
+
async function discoverApp(client, source, url) {
|
|
5389
|
+
switch (source) {
|
|
5390
|
+
case "mcp": return client.apps.discoverMcp({ url });
|
|
5391
|
+
case "openapi": return client.apps.discoverOpenApi({ url });
|
|
5392
|
+
case "graphql": return client.apps.discoverGraphql({ url });
|
|
5393
|
+
}
|
|
5394
|
+
}
|
|
5395
|
+
function buildCreateRequest(input, template) {
|
|
5396
|
+
const derived = deriveCustomAppDisplay(template, {
|
|
5397
|
+
url: input.url,
|
|
5398
|
+
mcp: input.source === "mcp"
|
|
5399
|
+
});
|
|
5400
|
+
const name = input.name?.trim() || derived.name;
|
|
5401
|
+
const description = input.description?.trim() || derived.description;
|
|
5402
|
+
const slug = input.slug?.trim() || slugifyAppName(name);
|
|
5403
|
+
const authKind = input.authKind ?? template.authKind;
|
|
5404
|
+
return {
|
|
5405
|
+
name,
|
|
5406
|
+
slug,
|
|
5407
|
+
description,
|
|
5408
|
+
source: input.source,
|
|
5409
|
+
url: input.url,
|
|
5410
|
+
authKind,
|
|
5411
|
+
...input.fields ? { fields: input.fields } : template.credentialFields ? { fields: template.credentialFields } : {},
|
|
5412
|
+
...template.credentialScheme ? { credentialScheme: template.credentialScheme } : {},
|
|
5413
|
+
...authKind === "oauth" && template.oauthScopes.length > 0 ? { oauthScopes: template.oauthScopes } : {}
|
|
5414
|
+
};
|
|
5415
|
+
}
|
|
5416
|
+
async function runAppCreateFromUrl(client, input) {
|
|
5417
|
+
if (input.authKind && input.source !== "mcp") throw new Error("--auth is only supported with --mcp");
|
|
5418
|
+
const discovery = await discoverApp(client, input.source, input.url);
|
|
5419
|
+
if (!discovery.detected) throw new Error(input.source === "mcp" ? "Couldn't reach this MCP server. Check the URL and try again." : input.source === "openapi" ? "Couldn't read this OpenAPI spec. Check the URL and try again." : "Couldn't introspect this GraphQL endpoint. Check the URL and try again.");
|
|
5420
|
+
const request = buildCreateRequest(input, discovery.template);
|
|
5421
|
+
if (input.preview) return {
|
|
5422
|
+
preview: true,
|
|
5423
|
+
detected: true,
|
|
5424
|
+
request,
|
|
5425
|
+
slug: await client.apps.checkSlug(request.slug)
|
|
5426
|
+
};
|
|
5427
|
+
return client.apps.create(request);
|
|
5428
|
+
}
|
|
5429
|
+
//#endregion
|
|
5382
5430
|
//#region src/commands/app/create.ts
|
|
5431
|
+
function resolveDiscoverSource(options) {
|
|
5432
|
+
const sources = [
|
|
5433
|
+
options.mcp ? {
|
|
5434
|
+
source: "mcp",
|
|
5435
|
+
url: options.mcp
|
|
5436
|
+
} : null,
|
|
5437
|
+
options.openapi ? {
|
|
5438
|
+
source: "openapi",
|
|
5439
|
+
url: options.openapi
|
|
5440
|
+
} : null,
|
|
5441
|
+
options.graphql ? {
|
|
5442
|
+
source: "graphql",
|
|
5443
|
+
url: options.graphql
|
|
5444
|
+
} : null
|
|
5445
|
+
].filter((entry) => entry !== null);
|
|
5446
|
+
if (sources.length > 1) throw new Error("Use only one of --mcp, --openapi, or --graphql");
|
|
5447
|
+
return sources[0] ?? null;
|
|
5448
|
+
}
|
|
5449
|
+
function parseAuthKind(value) {
|
|
5450
|
+
if (!value) return;
|
|
5451
|
+
if (value === "oauth" || value === "api_key") return value;
|
|
5452
|
+
throw new Error("--auth must be oauth or api_key");
|
|
5453
|
+
}
|
|
5454
|
+
function parseFieldOverrides(flags) {
|
|
5455
|
+
if (flags.length === 0) return;
|
|
5456
|
+
return parseCustomAppFields(flags);
|
|
5457
|
+
}
|
|
5383
5458
|
function registerAppCreateCommand(app) {
|
|
5384
|
-
app.command("create").description("Create a custom org
|
|
5459
|
+
app.command("create").description("Create a custom org app").option("--name <name>", "App display name").option("--slug <slug>", "App slug segment (defaults from name)").option("--description <description>", "App description").option("--field <field>", "Credential field as key, key:secret, key:optional, or key:secret:optional (repeatable)", collectValues$1, []).option("--mcp <url>", "Create from an MCP server URL (auto-detect auth)").option("--openapi <url>", "Create from an OpenAPI spec URL (auto-detect auth)").option("--graphql <url>", "Create from a GraphQL endpoint URL (auto-detect auth)").option("--auth <kind>", "Override detected auth: oauth or api_key (MCP only)").option("--preview", "Show the request that would be created without creating").action((options) => runCliCommand("Create app failed", async () => {
|
|
5385
5460
|
const config = createCliConfig();
|
|
5386
5461
|
const client = createCliPlatformClient(config);
|
|
5387
5462
|
await ensureActiveOrganization(config);
|
|
5463
|
+
const discovery = resolveDiscoverSource(options);
|
|
5464
|
+
if (discovery) {
|
|
5465
|
+
const result = await runAppCreateFromUrl(client, {
|
|
5466
|
+
source: discovery.source,
|
|
5467
|
+
url: discovery.url.trim(),
|
|
5468
|
+
name: options.name,
|
|
5469
|
+
slug: options.slug,
|
|
5470
|
+
description: options.description,
|
|
5471
|
+
authKind: parseAuthKind(options.auth),
|
|
5472
|
+
fields: parseFieldOverrides(options.field),
|
|
5473
|
+
preview: options.preview ?? false
|
|
5474
|
+
});
|
|
5475
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
5476
|
+
return;
|
|
5477
|
+
}
|
|
5478
|
+
if (!options.name?.trim()) throw new Error("--name is required for custom apps");
|
|
5479
|
+
if (!options.description?.trim()) throw new Error("--description is required for custom apps");
|
|
5388
5480
|
const slug = options.slug?.trim() || slugifyAppName(options.name);
|
|
5389
|
-
const
|
|
5481
|
+
const result = await runAppCreate(client, {
|
|
5390
5482
|
name: options.name.trim(),
|
|
5391
5483
|
slug,
|
|
5392
|
-
description: options.description,
|
|
5484
|
+
description: options.description.trim(),
|
|
5393
5485
|
source: "custom",
|
|
5394
5486
|
fields: parseCustomAppFields(options.field)
|
|
5395
|
-
});
|
|
5396
|
-
process.stdout.write(`${JSON.stringify(
|
|
5487
|
+
}, { preview: options.preview ?? false });
|
|
5488
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
5397
5489
|
}, void 0, { orgScoped: true }));
|
|
5398
5490
|
}
|
|
5399
5491
|
//#endregion
|
|
@@ -6114,7 +6206,7 @@ function registerBuildCommand(program) {
|
|
|
6114
6206
|
program.command("build").description("Build the keystroke project for production").option("--dir <path>", "Project directory", process.cwd()).action(async (options) => {
|
|
6115
6207
|
try {
|
|
6116
6208
|
const root = resolveProjectRoot(options.dir);
|
|
6117
|
-
const { buildApp } = await import("./dist-
|
|
6209
|
+
const { buildApp } = await import("./dist-5F59cW3X.mjs");
|
|
6118
6210
|
await buildApp({ root });
|
|
6119
6211
|
process.stdout.write(`Built ${root}\n`);
|
|
6120
6212
|
} catch (error) {
|
|
@@ -6168,7 +6260,7 @@ async function sleep(ms) {
|
|
|
6168
6260
|
}
|
|
6169
6261
|
async function buildDeployArchive(client, root, projectId, filter) {
|
|
6170
6262
|
if (filter?.length) {
|
|
6171
|
-
const { buildFilteredApp } = await import("./dist-
|
|
6263
|
+
const { buildFilteredApp } = await import("./dist-5F59cW3X.mjs");
|
|
6172
6264
|
const filtered = await buildFilteredApp({
|
|
6173
6265
|
root,
|
|
6174
6266
|
filter,
|
|
@@ -6190,7 +6282,7 @@ async function buildDeployArchive(client, root, projectId, filter) {
|
|
|
6190
6282
|
sourceFiles: filtered.sourceFiles
|
|
6191
6283
|
};
|
|
6192
6284
|
}
|
|
6193
|
-
const { buildApp } = await import("./dist-
|
|
6285
|
+
const { buildApp } = await import("./dist-5F59cW3X.mjs");
|
|
6194
6286
|
const { sourceFiles } = await buildApp({
|
|
6195
6287
|
root,
|
|
6196
6288
|
collectSources: true,
|
|
@@ -6309,7 +6401,7 @@ function runtimeChildEnv(parentEnv, overrides) {
|
|
|
6309
6401
|
//#region src/project/bootstrap-run.ts
|
|
6310
6402
|
/** Node args + env for `@keystrokehq/build` bootstrap (shared by start + dev). */
|
|
6311
6403
|
async function resolveBootstrapRun(options) {
|
|
6312
|
-
const { resolveRuntimeBuildArtifact } = await import("./dist-
|
|
6404
|
+
const { resolveRuntimeBuildArtifact } = await import("./dist-5F59cW3X.mjs");
|
|
6313
6405
|
const loader = pathToFileURL(resolveRuntimeBuildArtifact(options.runtimeNodeModules, "dist/runtime-loader.mjs")).href;
|
|
6314
6406
|
const bootstrap = resolveRuntimeBuildArtifact(options.runtimeNodeModules, "dist/standalone-bootstrap.mjs");
|
|
6315
6407
|
const args = [`--import=${loader}`];
|
|
@@ -6458,7 +6550,7 @@ async function runDev(options) {
|
|
|
6458
6550
|
process.on("SIGINT", shutdown);
|
|
6459
6551
|
process.on("SIGTERM", shutdown);
|
|
6460
6552
|
try {
|
|
6461
|
-
const { watchApp } = await import("./dist-
|
|
6553
|
+
const { watchApp } = await import("./dist-5F59cW3X.mjs");
|
|
6462
6554
|
await watchApp({
|
|
6463
6555
|
root,
|
|
6464
6556
|
clean: false,
|
|
@@ -6608,7 +6700,7 @@ const INIT_CATALOG_VERSIONS = {
|
|
|
6608
6700
|
vitest: "^4.1.7",
|
|
6609
6701
|
"@types/node": "^25.9.1"
|
|
6610
6702
|
};
|
|
6611
|
-
const INIT_KEYSTROKE_VERSION = "^0.1.
|
|
6703
|
+
const INIT_KEYSTROKE_VERSION = "^0.1.17";
|
|
6612
6704
|
//#endregion
|
|
6613
6705
|
//#region src/init/copy-template.ts
|
|
6614
6706
|
function renderTemplate(content, variables) {
|
|
@@ -7393,7 +7485,7 @@ async function runStart(options) {
|
|
|
7393
7485
|
const apiPort = Number(new URL(serverUrl).port || 80);
|
|
7394
7486
|
const runtimeNodeModules = resolveCliRuntimeNodeModules(resolveCliRoot(import.meta.url));
|
|
7395
7487
|
ensureNativeDeps(runtimeNodeModules);
|
|
7396
|
-
const { buildApp } = await import("./dist-
|
|
7488
|
+
const { buildApp } = await import("./dist-5F59cW3X.mjs");
|
|
7397
7489
|
await buildApp({
|
|
7398
7490
|
root,
|
|
7399
7491
|
clean: false
|
|
@@ -7977,7 +8069,7 @@ function createProgram() {
|
|
|
7977
8069
|
return program;
|
|
7978
8070
|
}
|
|
7979
8071
|
async function runCli(argv) {
|
|
7980
|
-
const { maybeAutoUpdate } = await import("./maybe-auto-update-
|
|
8072
|
+
const { maybeAutoUpdate } = await import("./maybe-auto-update-DVsgC8Cq.mjs");
|
|
7981
8073
|
await maybeAutoUpdate(argv);
|
|
7982
8074
|
createProgram().parse(argv);
|
|
7983
8075
|
}
|