@sanity/runtime-cli 17.1.0 → 17.2.0-blueprinit.gd1553d6

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 (104) hide show
  1. package/README.md +38 -28
  2. package/dist/actions/blueprinit/manifest.d.ts +13 -0
  3. package/dist/actions/blueprinit/manifest.js +57 -0
  4. package/dist/actions/blueprinit/studio.d.ts +6 -0
  5. package/dist/actions/blueprinit/studio.js +43 -0
  6. package/dist/actions/blueprinit/templates.d.ts +34 -0
  7. package/dist/actions/blueprinit/templates.js +83 -0
  8. package/dist/actions/blueprinit/workspace.d.ts +15 -0
  9. package/dist/actions/blueprinit/workspace.js +142 -0
  10. package/dist/actions/blueprints/assets.d.ts +2 -1
  11. package/dist/actions/blueprints/assets.js +17 -26
  12. package/dist/actions/blueprints/blueprint.d.ts +1 -1
  13. package/dist/actions/blueprints/pre-deploy.d.ts +29 -0
  14. package/dist/actions/blueprints/pre-deploy.js +164 -0
  15. package/dist/actions/blueprints/wait-for-operation.js +4 -0
  16. package/dist/actions/sanity/datasets.d.ts +15 -0
  17. package/dist/actions/sanity/datasets.js +26 -0
  18. package/dist/actions/sanity/examples.d.ts +4 -4
  19. package/dist/baseCommands.d.ts +4 -4
  20. package/dist/commands/blueprinit.d.ts +13 -0
  21. package/dist/commands/blueprinit.js +44 -0
  22. package/dist/commands/blueprints/add.d.ts +1 -1
  23. package/dist/commands/blueprints/config.d.ts +1 -1
  24. package/dist/commands/blueprints/deploy.d.ts +1 -1
  25. package/dist/commands/blueprints/destroy.d.ts +1 -1
  26. package/dist/commands/blueprints/doctor.d.ts +0 -1
  27. package/dist/commands/blueprints/doctor.js +3 -7
  28. package/dist/commands/blueprints/info.d.ts +1 -1
  29. package/dist/commands/blueprints/logs.d.ts +1 -1
  30. package/dist/commands/blueprints/mint-deploy-token.d.ts +1 -1
  31. package/dist/commands/blueprints/plan.d.ts +1 -1
  32. package/dist/commands/blueprints/promote.d.ts +1 -1
  33. package/dist/commands/blueprints/stacks.d.ts +1 -1
  34. package/dist/commands/functions/add.d.ts +1 -1
  35. package/dist/commands/functions/build.d.ts +1 -1
  36. package/dist/commands/functions/dev.d.ts +1 -1
  37. package/dist/commands/functions/env/add.d.ts +4 -1
  38. package/dist/commands/functions/env/add.js +6 -2
  39. package/dist/commands/functions/env/list.d.ts +4 -1
  40. package/dist/commands/functions/env/list.js +9 -3
  41. package/dist/commands/functions/env/remove.d.ts +4 -1
  42. package/dist/commands/functions/env/remove.js +9 -3
  43. package/dist/commands/functions/logs.d.ts +1 -1
  44. package/dist/commands/functions/test.d.ts +1 -1
  45. package/dist/constants.d.ts +1 -0
  46. package/dist/constants.js +1 -0
  47. package/dist/cores/blueprinit/adopt.d.ts +6 -0
  48. package/dist/cores/blueprinit/adopt.js +90 -0
  49. package/dist/cores/blueprinit/finish.d.ts +14 -0
  50. package/dist/cores/blueprinit/finish.js +36 -0
  51. package/dist/cores/blueprinit/fresh.d.ts +3 -0
  52. package/dist/cores/blueprinit/fresh.js +88 -0
  53. package/dist/cores/blueprinit/prompts.d.ts +4 -0
  54. package/dist/cores/blueprinit/prompts.js +14 -0
  55. package/dist/cores/blueprinit/selection.d.ts +15 -0
  56. package/dist/cores/blueprinit/selection.js +63 -0
  57. package/dist/cores/blueprinit/types.d.ts +13 -0
  58. package/dist/cores/blueprinit/types.js +1 -0
  59. package/dist/cores/blueprinit.d.ts +7 -0
  60. package/dist/cores/blueprinit.js +39 -0
  61. package/dist/cores/blueprints/deploy.js +18 -65
  62. package/dist/cores/blueprints/doctor.js +15 -12
  63. package/dist/cores/functions/build.js +3 -2
  64. package/dist/cores/functions/test.js +4 -2
  65. package/dist/server/app.js +8 -2
  66. package/dist/server/static/favicon-dark.svg +1 -0
  67. package/dist/server/static/favicon.svg +1 -0
  68. package/dist/server/static/index.html +1 -1
  69. package/dist/server/static/vendor/vendor.bundle.js +5 -0
  70. package/dist/utils/functions/child-process-wrapper.js +13 -171
  71. package/dist/utils/functions/child-runtime/console.d.ts +1 -0
  72. package/dist/utils/functions/child-runtime/console.js +50 -0
  73. package/dist/utils/functions/child-runtime/invoke.d.ts +4 -0
  74. package/dist/utils/functions/child-runtime/invoke.js +47 -0
  75. package/dist/utils/functions/child-runtime/resources.d.ts +4 -0
  76. package/dist/utils/functions/child-runtime/resources.js +59 -0
  77. package/dist/utils/functions/find-entry-point.d.ts +1 -1
  78. package/dist/utils/functions/find-entry-point.js +10 -12
  79. package/dist/utils/functions/invoke/local.js +1 -1
  80. package/dist/utils/functions/invoke/prepare.d.ts +1 -1
  81. package/dist/utils/functions/invoke/prepare.js +19 -8
  82. package/dist/utils/functions/package-json.d.ts +1 -2
  83. package/dist/utils/functions/package-json.js +4 -6
  84. package/dist/utils/functions/prepare-asset.d.ts +2 -2
  85. package/dist/utils/functions/prepare-asset.js +18 -7
  86. package/dist/utils/functions/resolve-dependencies.d.ts +4 -1
  87. package/dist/utils/functions/resolve-dependencies.js +5 -6
  88. package/dist/utils/functions/resource-to-arc.d.ts +1 -1
  89. package/dist/utils/functions/resource-to-arc.js +4 -5
  90. package/dist/utils/functions/should-transpile.d.ts +7 -1
  91. package/dist/utils/functions/should-transpile.js +10 -10
  92. package/dist/utils/functions/transpile/function.d.ts +4 -1
  93. package/dist/utils/functions/transpile/function.js +9 -14
  94. package/dist/utils/functions/transpile/verify-handler.js +1 -1
  95. package/dist/utils/logger.d.ts +7 -5
  96. package/dist/utils/logger.js +33 -1
  97. package/dist/utils/progress.d.ts +5 -0
  98. package/dist/utils/progress.js +40 -0
  99. package/dist/utils/studios/prepare-asset.d.ts +6 -0
  100. package/dist/utils/studios/prepare-asset.js +139 -0
  101. package/dist/utils/types.d.ts +9 -8
  102. package/dist/utils/types.js +2 -3
  103. package/oclif.manifest.json +1049 -951
  104. package/package.json +30 -23
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The returned proxy wraps a function so the API itself is callable.
3
+ * @param {Record<string, ResourceEntry[]>} resources
4
+ * @returns {ResourcesApi}
5
+ */
6
+ export function createResourcesApi(resources) {
7
+ const findByName = (name) => {
8
+ for (const group of Object.values(resources)) {
9
+ const found = group.find((r) => r.name === name)
10
+ if (found) return found
11
+ }
12
+ return undefined
13
+ }
14
+ let allCache
15
+ const all = () => (allCache ??= Object.values(resources).flat())
16
+
17
+ return /** @type {ResourcesApi} */ (
18
+ /** @type {unknown} */ (
19
+ /*
20
+ * The Proxy target is `findByName`, so invoking the API as a function —
21
+ * `context.resources('my-proj')` — bypasses the `get` trap entirely and
22
+ * calls `findByName` directly for a cross-type lookup by name.
23
+ */
24
+ new Proxy(findByName, {
25
+ get: (_target, prop) => {
26
+ // context.resources.all() — flat array of every resource across types
27
+ if (prop === 'all') return all
28
+ // [...context.resources] / for (const r of context.resources) — iterate all
29
+ if (prop === Symbol.iterator) {
30
+ return function* () {
31
+ yield* all()
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Symbol property access (other than iterator above) and `then`
37
+ * lookups return undefined. The `then` guard prevents the API from
38
+ * looking like a thenable, so `await context.resources` resolves to
39
+ * the proxy itself rather than hanging or unwrapping unexpectedly.
40
+ */
41
+ if (typeof prop !== 'string' || prop === 'then') {
42
+ return undefined
43
+ }
44
+
45
+ /**
46
+ * context.resources.<type>(name) — per-type lookup,
47
+ * e.g. context.resources.project('my-proj').
48
+ * Returns a function so the caller supplies the name;
49
+ * unknown types yield a function that always returns undefined.
50
+ */
51
+ return (/** @type {string} */ name) =>
52
+ Object.hasOwn(resources, prop)
53
+ ? resources[prop].find((r) => r.name === name)
54
+ : undefined
55
+ },
56
+ })
57
+ )
58
+ )
59
+ }
@@ -8,4 +8,4 @@
8
8
  * @returns The absolute path to the entry file.
9
9
  * @throws If the entry file cannot be determined.
10
10
  */
11
- export declare function findFunctionEntryPoint(srcPath: string, displayName?: string): Promise<string>;
11
+ export declare function findFunctionEntryPoint(functionPath: string, displayName?: string): Promise<string>;
@@ -1,6 +1,5 @@
1
1
  import { readFile, stat } from 'node:fs/promises';
2
2
  import { join, resolve } from 'node:path';
3
- import { cwd } from 'node:process';
4
3
  /**
5
4
  * Resolves the source path to an executable entry file path.
6
5
  *
@@ -11,27 +10,26 @@ import { cwd } from 'node:process';
11
10
  * @returns The absolute path to the entry file.
12
11
  * @throws If the entry file cannot be determined.
13
12
  */
14
- export async function findFunctionEntryPoint(srcPath, displayName) {
15
- const absolutePath = resolve(cwd(), srcPath);
13
+ export async function findFunctionEntryPoint(functionPath, displayName) {
16
14
  let stats;
17
15
  try {
18
- stats = await stat(absolutePath);
16
+ stats = await stat(functionPath);
19
17
  }
20
18
  catch (err) {
21
- throw new Error(`Source path not found or inaccessible: ${srcPath}`, { cause: err });
19
+ throw new Error(`Source path not found or inaccessible: ${functionPath}`, { cause: err });
22
20
  }
23
21
  if (stats.isFile()) {
24
22
  // It's already an entry file path
25
- return absolutePath;
23
+ return functionPath;
26
24
  }
27
25
  if (stats.isDirectory()) {
28
26
  // 1. Check package.json#main
29
27
  try {
30
- const pkgJsonPath = join(absolutePath, 'package.json');
28
+ const pkgJsonPath = join(functionPath, 'package.json');
31
29
  const pkgJsonContent = await readFile(pkgJsonPath, 'utf8');
32
30
  const pkgJson = JSON.parse(pkgJsonContent);
33
31
  if (pkgJson.main) {
34
- const mainPath = resolve(absolutePath, pkgJson.main);
32
+ const mainPath = resolve(functionPath, pkgJson.main);
35
33
  if (await fileExists(mainPath)) {
36
34
  return mainPath;
37
35
  }
@@ -43,20 +41,20 @@ export async function findFunctionEntryPoint(srcPath, displayName) {
43
41
  // Consider warning the user on invalid JSON though?
44
42
  }
45
43
  // 2. Check index.ts
46
- const indexTs = join(absolutePath, 'index.ts');
44
+ const indexTs = join(functionPath, 'index.ts');
47
45
  if (await fileExists(indexTs)) {
48
46
  return indexTs;
49
47
  }
50
48
  // 3. Check index.js
51
- const indexJs = join(absolutePath, 'index.js');
49
+ const indexJs = join(functionPath, 'index.js');
52
50
  if (await fileExists(indexJs)) {
53
51
  return indexJs;
54
52
  }
55
53
  const nameHint = displayName ? ` for function "${displayName}"` : '';
56
- throw new Error(`Could not determine entry file${nameHint} in directory: ${srcPath}. Looked for package.json#main, index.ts, index.js.`);
54
+ throw new Error(`Could not determine entry file${nameHint} in directory: ${functionPath}. Looked for package.json#main, index.ts, index.js.`);
57
55
  }
58
56
  // Should not happen if stat succeeded, but defensively handle
59
- throw new Error(`Source path is neither a file nor a directory: ${srcPath}`);
57
+ throw new Error(`Source path is neither a file nor a directory: ${functionPath}`);
60
58
  }
61
59
  /**
62
60
  * Checks if a file exists and is a file.
@@ -66,7 +66,7 @@ export default async function invoke(resource, payload, context, options) {
66
66
  // Acquire a shared, reference-counted build. Concurrent invokes of the same
67
67
  // function reuse one transpile + temp package.json instead of racing on the
68
68
  // per-function build paths; the build is torn down once every invoke releases.
69
- const build = acquireFunctionBuild(resource);
69
+ const build = acquireFunctionBuild(resource, context.blueprintFileDir);
70
70
  let functionPath;
71
71
  let bundleTimings;
72
72
  try {
@@ -17,4 +17,4 @@ export interface FunctionBuild {
17
17
  * caller MUST call `release()` exactly once when its child has exited, so the
18
18
  * shared artifacts are torn down only after the last in-flight invoke finishes.
19
19
  */
20
- export declare function acquireFunctionBuild(resource: FunctionResource): FunctionBuild;
20
+ export declare function acquireFunctionBuild(resource: FunctionResource, blueprintFileDir: string): FunctionBuild;
@@ -1,3 +1,4 @@
1
+ import path from 'node:path';
1
2
  import { findFunctionEntryPoint } from '../find-entry-point.js';
2
3
  import { cleanupTempPackageJson, createTempPackageJson, doesPackageJsonExists, } from '../package-json.js';
3
4
  import { resolveResourceDependencies } from '../resolve-dependencies.js';
@@ -22,34 +23,44 @@ function buildKey(resource) {
22
23
  * caller MUST call `release()` exactly once when its child has exited, so the
23
24
  * shared artifacts are torn down only after the last in-flight invoke finishes.
24
25
  */
25
- export function acquireFunctionBuild(resource) {
26
+ export function acquireFunctionBuild(resource, blueprintFileDir) {
26
27
  const key = buildKey(resource);
27
28
  let entry = builds.get(key);
28
29
  if (!entry) {
29
30
  let cleanupBundle = async () => { };
30
- let functionPath = '';
31
+ const resolvedFunctionPath = path.resolve(blueprintFileDir, resource.src);
32
+ let functionPath = resolvedFunctionPath;
31
33
  let createdTempPackageJson = false;
32
34
  // If no package.json exists we create a temporary one to avoid the
33
35
  // "module type" warning from node.
34
- const existingPackageJson = doesPackageJsonExists(resource);
36
+ const existingPackageJson = doesPackageJsonExists(functionPath);
35
37
  const ready = (async () => {
36
38
  if (!resource.src) {
37
39
  throw new Error(`Function resource "${resource.name}" is missing the 'src' property.`);
38
40
  }
39
41
  let bundleTimings;
40
- const shouldTranspile = await shouldTranspileFunction(resource);
41
- if (shouldTranspile) {
42
- const transpileResult = await transpileFunction(resource);
42
+ const shouldTranspile = await shouldTranspileFunction(resource, functionPath);
43
+ if (shouldTranspile.transpile) {
44
+ const transpileResult = await transpileFunction({
45
+ resource,
46
+ functionPath,
47
+ entryPoint: shouldTranspile.entryPoint,
48
+ });
43
49
  functionPath = await findFunctionEntryPoint(transpileResult.outputDir);
44
50
  bundleTimings = transpileResult.timings;
45
51
  cleanupBundle = transpileResult.cleanup;
46
52
  }
47
53
  else {
48
- functionPath = await findFunctionEntryPoint(resource.src, resource.displayName ?? resource.name);
54
+ functionPath = await findFunctionEntryPoint(functionPath, resource.displayName ?? resource.name);
49
55
  }
50
56
  const shouldResolveDependencies = await shouldAutoResolveDependencies(resource);
51
57
  if (shouldResolveDependencies && existingPackageJson) {
52
- await resolveResourceDependencies(resource, { transpiled: shouldTranspile });
58
+ await resolveResourceDependencies({
59
+ resource,
60
+ functionPath: resolvedFunctionPath,
61
+ blueprintFileDir,
62
+ transpiled: shouldTranspile.transpile,
63
+ });
53
64
  }
54
65
  if (!existingPackageJson) {
55
66
  createTempPackageJson(functionPath);
@@ -1,4 +1,3 @@
1
- import type { FunctionResource } from '../types.js';
2
- export declare function doesPackageJsonExists(resource: FunctionResource): boolean;
1
+ export declare function doesPackageJsonExists(functionPath: string): boolean;
3
2
  export declare function createTempPackageJson(functionPath: string): boolean;
4
3
  export declare function cleanupTempPackageJson(functionPath: string): boolean;
@@ -1,17 +1,15 @@
1
1
  import { existsSync, rmSync, writeFileSync } from 'node:fs';
2
- import { dirname, join, resolve } from 'node:path';
3
- import { cwd } from 'node:process';
2
+ import { dirname, join } from 'node:path';
4
3
  function getPackageJsonPath(functionPath) {
5
4
  const functionDir = dirname(functionPath);
6
5
  return join(functionDir, 'package.json');
7
6
  }
8
- export function doesPackageJsonExists(resource) {
9
- if (!resource.src) {
7
+ export function doesPackageJsonExists(functionPath) {
8
+ if (!functionPath) {
10
9
  // Cannot determine without a source path
11
10
  return false;
12
11
  }
13
- const absolutePath = resolve(cwd(), resource.src);
14
- const packageJsonPath = join(absolutePath, 'package.json');
12
+ const packageJsonPath = join(functionPath, 'package.json');
15
13
  return existsSync(packageJsonPath);
16
14
  }
17
15
  export function createTempPackageJson(functionPath) {
@@ -1,6 +1,6 @@
1
1
  import type { AssetPrepResult, FunctionResource, InstallerType } from '../types.js';
2
- export declare function prepareAsset({ resource, }: {
2
+ export declare function prepareAsset({ blueprintFileDir, resource, installer, }: {
3
+ blueprintFileDir: string;
3
4
  resource: FunctionResource;
4
- }, { installer }?: {
5
5
  installer?: InstallerType;
6
6
  }): Promise<AssetPrepResult>;
@@ -1,7 +1,6 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { rm, stat } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
- import { cwd } from 'node:process';
5
4
  import { MAX_ASSET_SIZE } from '../../constants.js';
6
5
  import { detectNativeModules, errorMessage } from './detect-native-modules.js';
7
6
  import { getFolderSize } from './get-folder-size.js';
@@ -9,16 +8,22 @@ import { resolveResourceDependencies } from './resolve-dependencies.js';
9
8
  import { shouldAutoResolveDependencies } from './should-auto-resolve-deps.js';
10
9
  import { shouldTranspileFunction } from './should-transpile.js';
11
10
  import { transpileFunction } from './transpile/function.js';
12
- export async function prepareAsset({ resource, }, { installer } = {}) {
11
+ export async function prepareAsset({ blueprintFileDir, resource, installer, }) {
13
12
  if (!resource.src)
14
13
  throw new Error('Resource src is required');
15
- let functionPath = path.join(cwd(), resource.src);
14
+ const resolvedFunctionPath = path.resolve(blueprintFileDir, resource.src);
15
+ let functionPath = resolvedFunctionPath;
16
16
  let cleanup = async () => { };
17
17
  let wasBundled = false;
18
- const shouldTranspile = await shouldTranspileFunction(resource);
19
- if (shouldTranspile) {
18
+ const shouldTranspile = await shouldTranspileFunction(resource, functionPath);
19
+ if (shouldTranspile.transpile) {
20
20
  try {
21
- const result = await transpileFunction(resource, { installer });
21
+ const result = await transpileFunction({
22
+ resource,
23
+ functionPath,
24
+ entryPoint: shouldTranspile.entryPoint,
25
+ installer,
26
+ });
22
27
  functionPath = result.outputDir;
23
28
  cleanup = result.cleanup;
24
29
  wasBundled = result.bundled;
@@ -29,7 +34,13 @@ export async function prepareAsset({ resource, }, { installer } = {}) {
29
34
  }
30
35
  const shouldResolveDependencies = await shouldAutoResolveDependencies(resource);
31
36
  if (shouldResolveDependencies && !wasBundled) {
32
- await resolveResourceDependencies(resource, { transpiled: shouldTranspile, installer });
37
+ await resolveResourceDependencies({
38
+ resource,
39
+ functionPath: resolvedFunctionPath,
40
+ blueprintFileDir,
41
+ transpiled: shouldTranspile.transpile,
42
+ installer,
43
+ });
33
44
  await removeArcAutoInstallPackageJson(functionPath);
34
45
  }
35
46
  if (existsSync(path.join(functionPath, 'node_modules'))) {
@@ -1,5 +1,8 @@
1
1
  import type { FunctionResource, InstallerType } from '../types.js';
2
- export declare function resolveResourceDependencies(resource: FunctionResource, { transpiled, installer, }: {
2
+ export declare function resolveResourceDependencies({ resource, transpiled, blueprintFileDir, functionPath, installer, }: {
3
+ resource: FunctionResource;
4
+ blueprintFileDir: string;
5
+ functionPath: string;
3
6
  transpiled: boolean;
4
7
  installer?: InstallerType;
5
8
  }): Promise<void>;
@@ -3,18 +3,17 @@ import { join } from 'node:path';
3
3
  import hydrate from '@architect/hydrate';
4
4
  import inventory from '@architect/inventory';
5
5
  import { convertResourceToArcFormat } from './resource-to-arc.js';
6
- export async function resolveResourceDependencies(resource, { transpiled, installer, }) {
7
- const rawArc = await convertResourceToArcFormat(resource, transpiled);
8
- const inv = await inventory({ rawArc });
9
- const cwd = inv.inv._project.cwd;
6
+ export async function resolveResourceDependencies({ resource, transpiled, blueprintFileDir, functionPath, installer, }) {
7
+ const rawArc = await convertResourceToArcFormat(resource, functionPath, transpiled);
8
+ const inv = await inventory({ rawArc, cwd: blueprintFileDir });
10
9
  let installType = 'npm';
11
10
  if (installer) {
12
11
  installType = installer;
13
12
  }
14
- else if (existsSync(join(cwd, 'pnpm-lock.yaml'))) {
13
+ else if (existsSync(join(blueprintFileDir, 'pnpm-lock.yaml'))) {
15
14
  installType = 'pnpm';
16
15
  }
17
- else if (existsSync(join(cwd, 'yarn.lock'))) {
16
+ else if (existsSync(join(blueprintFileDir, 'yarn.lock'))) {
18
17
  installType = 'yarn';
19
18
  }
20
19
  try {
@@ -1,2 +1,2 @@
1
1
  import type { FunctionResource } from '../types.js';
2
- export declare function convertResourceToArcFormat(resource: FunctionResource, transpiled: boolean): Promise<string>;
2
+ export declare function convertResourceToArcFormat(resource: FunctionResource, functionPath: string, transpiled: boolean): Promise<string>;
@@ -1,16 +1,15 @@
1
1
  import { stat } from 'node:fs/promises';
2
- import { resolve, sep } from 'node:path';
3
- import { cwd } from 'node:process';
4
- export async function convertResourceToArcFormat(resource, transpiled) {
2
+ import { sep } from 'node:path';
3
+ export async function convertResourceToArcFormat(resource, functionPath, transpiled) {
5
4
  if (!resource.src) {
6
5
  throw Error('Missing `resource.src` property');
7
6
  }
8
7
  // Get stats from file
9
- const stats = await stat(resolve(cwd(), resource.src));
8
+ const stats = await stat(functionPath);
10
9
  // Convert resource.src to arc file path format
11
10
  const srcPath = resource.src?.split(sep).join('/');
12
11
  const entryDir = stats.isFile() ? srcPath.substring(0, srcPath.lastIndexOf('/')) : srcPath;
13
- const functionPath = transpiled ? `${entryDir}/.build/function-${resource.name}` : entryDir;
12
+ functionPath = transpiled ? `${entryDir}/.build/function-${resource.name}` : entryDir;
14
13
  return `@app
15
14
  hydrate-function
16
15
 
@@ -1,2 +1,8 @@
1
1
  import type { FunctionResource } from '../types.js';
2
- export declare function shouldTranspileFunction(resource: FunctionResource): Promise<boolean>;
2
+ export type ShouldTranspileResult = {
3
+ transpile: true;
4
+ entryPoint: string;
5
+ } | {
6
+ transpile: false;
7
+ };
8
+ export declare function shouldTranspileFunction(resource: FunctionResource, functionPath: string): Promise<ShouldTranspileResult>;
@@ -1,22 +1,22 @@
1
1
  import { findFunctionEntryPoint } from './find-entry-point.js';
2
- export async function shouldTranspileFunction(resource) {
3
- if ('transpile' in resource && typeof resource.transpile === 'boolean') {
4
- return resource.transpile;
5
- }
6
- if (!resource.src) {
7
- // Cannot determine without a source path
8
- return false;
2
+ export async function shouldTranspileFunction(resource, functionPath) {
3
+ const hasTranspile = 'transpile' in resource && typeof resource.transpile === 'boolean';
4
+ if (!functionPath || (hasTranspile && resource.transpile === false)) {
5
+ return { transpile: false };
9
6
  }
10
7
  try {
11
8
  // 2. Find the actual entry point
12
- const entryPoint = await findFunctionEntryPoint(resource.src, resource.displayName ?? resource.name);
9
+ const entryPoint = await findFunctionEntryPoint(functionPath, resource.displayName ?? resource.name);
13
10
  // 3. Check if the resolved entry point is a TypeScript file
14
- return entryPoint.endsWith('.ts');
11
+ return {
12
+ entryPoint,
13
+ transpile: hasTranspile ? resource.transpile === true : entryPoint.endsWith('.ts'),
14
+ };
15
15
  }
16
16
  catch (err) {
17
17
  // If we cannot find the entry point, we cannot determine if it's TS.
18
18
  // Log a warning and default to false (don't bundle).
19
19
  console.warn(`[warn] Could not determine entry point for function "${resource.displayName ?? resource.name}" while checking if transpiling is needed: ${err instanceof Error ? err.message : err}`);
20
- return false;
20
+ return { transpile: false };
21
21
  }
22
22
  }
@@ -1,6 +1,9 @@
1
1
  import type { FunctionResource, InstallerType } from '../../types.js';
2
2
  export declare const resolveViteRoot: (entry: string) => string;
3
- export declare function transpileFunction(resource: FunctionResource, { installer }?: {
3
+ export declare function transpileFunction({ resource, functionPath, entryPoint, installer, }: {
4
+ resource: FunctionResource;
5
+ functionPath: string;
6
+ entryPoint: string;
4
7
  installer?: InstallerType;
5
8
  }): Promise<{
6
9
  type: string;
@@ -3,9 +3,9 @@ import path from 'node:path';
3
3
  import { performance } from 'node:perf_hooks';
4
4
  import { cwd } from 'node:process';
5
5
  import * as find from 'empathic/find';
6
+ import stripAnsi from 'strip-ansi';
6
7
  import { build as viteBuild } from 'vite';
7
8
  import { detectNativeModulesPlugin } from '../detect-native-modules.js';
8
- import { findFunctionEntryPoint } from '../find-entry-point.js';
9
9
  import { cleanupSourceMaps } from './cleanup-source-maps.js';
10
10
  import { createPnpmRequire } from './pnpm.js';
11
11
  import { verifyHandler } from './verify-handler.js';
@@ -13,23 +13,18 @@ export const resolveViteRoot = (entry) => {
13
13
  const nodeModulesDir = find.dir('node_modules', { cwd: entry });
14
14
  return nodeModulesDir ? path.dirname(nodeModulesDir) : entry;
15
15
  };
16
- export async function transpileFunction(resource, { installer } = {}) {
16
+ export async function transpileFunction({ resource, functionPath, entryPoint, installer, }) {
17
17
  if (!resource.src)
18
18
  throw new Error('Resource src is required');
19
19
  if (!resource.name)
20
20
  throw new Error('Resource name is required');
21
21
  const timings = {};
22
22
  const transpileStart = performance.now();
23
- const sourcePath = path.resolve(cwd(), resource.src);
24
- const stats = await stat(sourcePath);
25
- const fnDisplayName = resource.displayName ?? resource.name;
26
- const findEntryStart = performance.now();
27
- const entry = await findFunctionEntryPoint(sourcePath, fnDisplayName);
28
- timings['transpile:findEntry'] = performance.now() - findEntryStart;
29
- const entryDir = stats.isFile() ? path.dirname(sourcePath) : sourcePath;
23
+ const stats = await stat(functionPath);
24
+ const entryDir = stats.isFile() ? path.dirname(functionPath) : functionPath;
30
25
  const outputPathStart = performance.now();
31
26
  const outputDir = await getTranspileOutputPath(entryDir, resource.name);
32
- const outputFile = path.join(outputDir, getOutputFilename(entry));
27
+ const outputFile = path.join(outputDir, getOutputFilename(entryPoint));
33
28
  const fnRootDir = resolveViteRoot(entryDir);
34
29
  timings['transpile:setupOutput'] = performance.now() - outputPathStart;
35
30
  async function cleanupTmpDir() {
@@ -51,10 +46,10 @@ export async function transpileFunction(resource, { installer } = {}) {
51
46
  sourcemap: true,
52
47
  ssr: true,
53
48
  rolldownOptions: {
54
- input: entry,
49
+ input: entryPoint,
55
50
  output: {
56
51
  format: 'esm',
57
- entryFileNames: getOutputFilename(entry),
52
+ entryFileNames: getOutputFilename(entryPoint),
58
53
  ...(bundle
59
54
  ? {}
60
55
  : {
@@ -86,7 +81,7 @@ export async function transpileFunction(resource, { installer } = {}) {
86
81
  await writeTranspiledPackageJson(entryDir, outputFile);
87
82
  timings['transpile:writePackage'] = performance.now() - pkgStart;
88
83
  const cleanupStart = performance.now();
89
- await cleanupSourceMaps(sourcePath, outputDir);
84
+ await cleanupSourceMaps(functionPath, outputDir);
90
85
  timings['transpile:cleanupMaps'] = performance.now() - cleanupStart;
91
86
  timings.bundle = performance.now() - transpileStart;
92
87
  return {
@@ -100,7 +95,7 @@ export async function transpileFunction(resource, { installer } = {}) {
100
95
  }
101
96
  catch (err) {
102
97
  await cleanupTmpDir();
103
- throw new Error(`Transpiling of function failed: ${formatBuildError(err)}`, {
98
+ throw new Error(`Transpiling of function failed: ${stripAnsi(formatBuildError(err))}`, {
104
99
  cause: err,
105
100
  });
106
101
  }
@@ -4,7 +4,7 @@ export async function verifyHandler(result) {
4
4
  }
5
5
  const outputs = (Array.isArray(result) ? result : [result]).flatMap(({ output }) => output);
6
6
  const bundledIndex = outputs.find((output) => output.type === 'chunk' && output.isEntry && output.fileName === 'index.js');
7
- if (!bundledIndex || bundledIndex.type !== 'chunk') {
7
+ if (bundledIndex?.type !== 'chunk') {
8
8
  throw new Error('Unexpected build output, no bundled index found');
9
9
  }
10
10
  if (!bundledIndex.exports.includes('handler')) {
@@ -6,11 +6,13 @@ export declare function Logger(log: (msg: string) => void, flags?: {
6
6
  }): {
7
7
  (msg: string): void;
8
8
  isTraceEnabled: boolean;
9
- trace(formatter: unknown, ...args: unknown[]): false | void;
10
- verbose(formatter: unknown, ...args: unknown[]): false | void;
11
- info(formatter: unknown, ...args: unknown[]): false | void;
12
- warn(formatter: unknown, ...args: unknown[]): false | void;
13
- error(formatter: unknown, ...args: unknown[]): false | void;
9
+ trace: (formatter: unknown, ...args: unknown[]) => void | false;
10
+ verbose: (formatter: unknown, ...args: unknown[]) => void | false;
11
+ info: (formatter: unknown, ...args: unknown[]) => void | false;
12
+ warn: (formatter: unknown, ...args: unknown[]) => void | false;
13
+ error: (formatter: unknown, ...args: unknown[]) => void | false;
14
+ showProgress: (percent?: number) => void;
15
+ clearProgress: () => void;
14
16
  ora: typeof ora;
15
17
  };
16
18
  export type Logger = ReturnType<typeof Logger>;
@@ -1,5 +1,6 @@
1
1
  import { format } from 'node:util';
2
2
  import ora from 'ora';
3
+ import { clearProgress, showBusy, showError, showProgress } from './progress.js';
3
4
  var LogLevel;
4
5
  (function (LogLevel) {
5
6
  LogLevel[LogLevel["TRACE"] = 0] = "TRACE";
@@ -19,16 +20,47 @@ export function Logger(log, flags = {}) {
19
20
  logger.info = (formatter, ...args) => level <= LogLevel.INFO && logger(format(formatter, ...args));
20
21
  logger.warn = (formatter, ...args) => level <= LogLevel.WARN && logger(format(formatter, ...args));
21
22
  logger.error = (formatter, ...args) => level <= LogLevel.ERROR && logger(format(formatter, ...args));
23
+ logger.showProgress = (percent) => {
24
+ if (flags.json)
25
+ return;
26
+ if (percent === undefined)
27
+ showBusy();
28
+ else
29
+ showProgress(percent);
30
+ };
31
+ logger.clearProgress = () => {
32
+ if (flags.json)
33
+ return;
34
+ clearProgress();
35
+ };
22
36
  const oraWrapper = (opts) => {
23
37
  if (flags.json)
24
38
  return createOraLineLoggingWrapper(opts, logger);
25
39
  if (level >= LogLevel.INFO)
26
- return ora(opts);
40
+ return withTerminalProgress(ora(opts));
27
41
  return createOraLineLoggingWrapper(opts, logger);
28
42
  };
29
43
  logger.ora = oraWrapper;
30
44
  return logger;
31
45
  }
46
+ function withTerminalProgress(spinner) {
47
+ const wrap = (name, effect) => {
48
+ if (typeof spinner[name] !== 'function')
49
+ return;
50
+ const original = spinner[name].bind(spinner);
51
+ spinner[name] = (...args) => {
52
+ const result = original(...args);
53
+ effect();
54
+ return result;
55
+ };
56
+ };
57
+ wrap('start', showBusy);
58
+ wrap('fail', showError);
59
+ for (const name of ['stop', 'succeed', 'warn', 'info', 'stopAndPersist']) {
60
+ wrap(name, clearProgress);
61
+ }
62
+ return spinner;
63
+ }
32
64
  /**
33
65
  * An ora-like wrapper that uses standard line output logging instead of rendering a spinner; used in verbose and trace modes.
34
66
  */
@@ -0,0 +1,5 @@
1
+ export declare function showProgress(percent: number): void;
2
+ export declare function showBusy(): void;
3
+ export declare function showError(): void;
4
+ export declare function showPaused(percent: number): void;
5
+ export declare function clearProgress(): void;
@@ -0,0 +1,40 @@
1
+ import { stderr } from 'node:process';
2
+ import { onExit } from 'signal-exit';
3
+ const ST = '\x1b\\';
4
+ const STATES = {
5
+ clear: 0,
6
+ normal: 1,
7
+ error: 2,
8
+ paused: 4,
9
+ busy: 3,
10
+ };
11
+ let exitHookRegistered = false;
12
+ function write(state, value = 0) {
13
+ if (!stderr.isTTY)
14
+ return;
15
+ if (!exitHookRegistered) {
16
+ exitHookRegistered = true;
17
+ function clear() {
18
+ stderr.write(`\x1b]9;4;0;0${ST}`);
19
+ }
20
+ // arc/utils SIGINT handler clobbers our signal-exit; luckily it then calls process.exit()
21
+ process.once('exit', clear); // triggered by arc/utils SIGINT handler
22
+ onExit(clear); // triggered by all other exit paths
23
+ }
24
+ stderr.write(`\x1b]9;4;${STATES[state]};${Math.round(value)}${ST}`);
25
+ }
26
+ export function showProgress(percent) {
27
+ write('normal', Math.max(0, Math.min(100, percent)));
28
+ }
29
+ export function showBusy() {
30
+ write('busy');
31
+ }
32
+ export function showError() {
33
+ write('error', 100);
34
+ }
35
+ export function showPaused(percent) {
36
+ write('paused', Math.max(0, Math.min(100, percent)));
37
+ }
38
+ export function clearProgress() {
39
+ write('clear');
40
+ }
@@ -0,0 +1,6 @@
1
+ import type { BlueprintStudioResource } from '@sanity/blueprints';
2
+ import type { AssetPrepResult } from '../types.js';
3
+ export declare function prepareStudioAsset({ blueprintFileDir, resource, }: {
4
+ blueprintFileDir: string;
5
+ resource: BlueprintStudioResource;
6
+ }): Promise<AssetPrepResult>;