@sanity/runtime-cli 14.8.4 → 14.8.5

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/README.md CHANGED
@@ -20,7 +20,7 @@ $ npm install -g @sanity/runtime-cli
20
20
  $ sanity-run COMMAND
21
21
  running command...
22
22
  $ sanity-run (--version)
23
- @sanity/runtime-cli/14.8.4 linux-x64 node-v24.14.0
23
+ @sanity/runtime-cli/14.8.5 linux-x64 node-v24.14.1
24
24
  $ sanity-run --help [COMMAND]
25
25
  USAGE
26
26
  $ sanity-run COMMAND
@@ -101,7 +101,7 @@ EXAMPLES
101
101
  $ sanity-run blueprints add function --name my-function --fn-type document-create --fn-type document-update --lang js
102
102
  ```
103
103
 
104
- _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/blueprints/add.ts)_
104
+ _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/blueprints/add.ts)_
105
105
 
106
106
  ## `sanity-run blueprints config`
107
107
 
@@ -140,7 +140,7 @@ EXAMPLES
140
140
  $ sanity-run blueprints config --edit --project-id <projectId> --stack <name-or-id>
141
141
  ```
142
142
 
143
- _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/blueprints/config.ts)_
143
+ _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/blueprints/config.ts)_
144
144
 
145
145
  ## `sanity-run blueprints deploy`
146
146
 
@@ -179,7 +179,7 @@ EXAMPLES
179
179
  $ sanity-run blueprints deploy --fn-installer npm
180
180
  ```
181
181
 
182
- _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/blueprints/deploy.ts)_
182
+ _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/blueprints/deploy.ts)_
183
183
 
184
184
  ## `sanity-run blueprints destroy`
185
185
 
@@ -215,7 +215,7 @@ EXAMPLES
215
215
  $ sanity-run blueprints destroy --stack <name-or-id> --project-id <projectId> --force --no-wait
216
216
  ```
217
217
 
218
- _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/blueprints/destroy.ts)_
218
+ _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/blueprints/destroy.ts)_
219
219
 
220
220
  ## `sanity-run blueprints doctor`
221
221
 
@@ -242,7 +242,7 @@ DESCRIPTION
242
242
  issues.
243
243
  ```
244
244
 
245
- _See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/blueprints/doctor.ts)_
245
+ _See code: [src/commands/blueprints/doctor.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/blueprints/doctor.ts)_
246
246
 
247
247
  ## `sanity-run blueprints info`
248
248
 
@@ -274,7 +274,7 @@ EXAMPLES
274
274
  $ sanity-run blueprints info --stack <name-or-id>
275
275
  ```
276
276
 
277
- _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/blueprints/info.ts)_
277
+ _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/blueprints/info.ts)_
278
278
 
279
279
  ## `sanity-run blueprints init [DIR]`
280
280
 
@@ -328,7 +328,7 @@ EXAMPLES
328
328
  $ sanity-run blueprints init --blueprint-type <json|js|ts> --stack-name <stackName>
329
329
  ```
330
330
 
331
- _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/blueprints/init.ts)_
331
+ _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/blueprints/init.ts)_
332
332
 
333
333
  ## `sanity-run blueprints logs`
334
334
 
@@ -359,7 +359,7 @@ EXAMPLES
359
359
  $ sanity-run blueprints logs --watch
360
360
  ```
361
361
 
362
- _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/blueprints/logs.ts)_
362
+ _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/blueprints/logs.ts)_
363
363
 
364
364
  ## `sanity-run blueprints plan`
365
365
 
@@ -387,7 +387,7 @@ EXAMPLES
387
387
  $ sanity-run blueprints plan
388
388
  ```
389
389
 
390
- _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/blueprints/plan.ts)_
390
+ _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/blueprints/plan.ts)_
391
391
 
392
392
  ## `sanity-run blueprints stacks`
393
393
 
@@ -419,7 +419,7 @@ EXAMPLES
419
419
  $ sanity-run blueprints stacks --organization-id <organizationId>
420
420
  ```
421
421
 
422
- _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/blueprints/stacks.ts)_
422
+ _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/blueprints/stacks.ts)_
423
423
 
424
424
  ## `sanity-run functions add`
425
425
 
@@ -472,7 +472,7 @@ EXAMPLES
472
472
  $ sanity-run functions add --name my-function --type document-create --type document-update --lang js
473
473
  ```
474
474
 
475
- _See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/functions/add.ts)_
475
+ _See code: [src/commands/functions/add.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/functions/add.ts)_
476
476
 
477
477
  ## `sanity-run functions dev`
478
478
 
@@ -508,7 +508,7 @@ EXAMPLES
508
508
  $ sanity-run functions dev --timeout 60
509
509
  ```
510
510
 
511
- _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/functions/dev.ts)_
511
+ _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/functions/dev.ts)_
512
512
 
513
513
  ## `sanity-run functions env add NAME KEY VALUE`
514
514
 
@@ -539,7 +539,7 @@ EXAMPLES
539
539
  $ sanity-run functions env add MyFunction API_URL https://api.example.com/
540
540
  ```
541
541
 
542
- _See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/functions/env/add.ts)_
542
+ _See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/functions/env/add.ts)_
543
543
 
544
544
  ## `sanity-run functions env list NAME`
545
545
 
@@ -567,7 +567,7 @@ EXAMPLES
567
567
  $ sanity-run functions env list MyFunction
568
568
  ```
569
569
 
570
- _See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/functions/env/list.ts)_
570
+ _See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/functions/env/list.ts)_
571
571
 
572
572
  ## `sanity-run functions env remove NAME KEY`
573
573
 
@@ -597,7 +597,7 @@ EXAMPLES
597
597
  $ sanity-run functions env remove MyFunction API_URL
598
598
  ```
599
599
 
600
- _See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/functions/env/remove.ts)_
600
+ _See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/functions/env/remove.ts)_
601
601
 
602
602
  ## `sanity-run functions logs [NAME]`
603
603
 
@@ -639,7 +639,7 @@ EXAMPLES
639
639
  $ sanity-run functions logs <name> --delete
640
640
  ```
641
641
 
642
- _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/functions/logs.ts)_
642
+ _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/functions/logs.ts)_
643
643
 
644
644
  ## `sanity-run functions test [NAME]`
645
645
 
@@ -697,7 +697,7 @@ EXAMPLES
697
697
  $ sanity-run functions test <name> --event update --data-before '{ "title": "before" }' --data-after '{ "title": "after" }'
698
698
  ```
699
699
 
700
- _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.4/src/commands/functions/test.ts)_
700
+ _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v14.8.5/src/commands/functions/test.ts)_
701
701
 
702
702
  ## `sanity-run help [COMMAND]`
703
703
 
@@ -1,11 +1,10 @@
1
- import type { BlueprintResource } from '@sanity/blueprints';
2
1
  import AdmZip from 'adm-zip';
3
2
  import type { Logger } from '../../utils/logger.js';
4
- import type { AuthParams, InstallerType } from '../../utils/types.js';
3
+ import type { AssetResource, AuthParams, InstallerType } from '../../utils/types.js';
5
4
  export declare const ASSET_CHECK_URL: string;
6
5
  export declare const ASSET_STASH_URL: string;
7
6
  export declare function stashAsset({ resource, auth, logger, installer, }: {
8
- resource: BlueprintResource;
7
+ resource: AssetResource;
9
8
  auth: AuthParams;
10
9
  logger: Logger;
11
10
  installer?: InstallerType;
@@ -3,7 +3,6 @@ import fs from 'node:fs';
3
3
  import AdmZip from 'adm-zip';
4
4
  import config from '../../config.js';
5
5
  import { CONVERT_BYTES_TO_MB, MAX_ASSET_SIZE } from '../../constants.js';
6
- import { detectNativeModules } from '../../utils/functions/detect-native-modules.js';
7
6
  import { prepareAsset as prepareFunctionAsset } from '../../utils/functions/prepare-asset.js';
8
7
  import getHeaders from '../../utils/get-headers.js';
9
8
  import { createTracedFetch } from '../../utils/traced-fetch.js';
@@ -49,7 +48,7 @@ export async function stashAsset({ resource, auth, logger, installer, }) {
49
48
  else {
50
49
  return {
51
50
  success: false,
52
- error: `Invalid resource type ${resource.type} for asset processing`,
51
+ error: `Unexpected resource for asset processing`,
53
52
  };
54
53
  }
55
54
  return await stashSingleAsset({
@@ -67,16 +66,7 @@ export async function stashAsset({ resource, auth, logger, installer, }) {
67
66
  }
68
67
  }
69
68
  async function prepareStudioAsset({ resource, }) {
70
- if (!('src' in resource) || typeof resource.src !== 'string') {
71
- return {
72
- success: false,
73
- async cleanup() {
74
- // no op
75
- },
76
- error: `Resource of type '${resource.type}' must have a 'src' property`,
77
- };
78
- }
79
- else if (!fs.existsSync(resource.src)) {
69
+ if (!fs.existsSync(resource.src)) {
80
70
  return {
81
71
  success: false,
82
72
  async cleanup() {
@@ -171,12 +161,6 @@ export async function pathToB64ZipHash(path) {
171
161
  if (size > MAX_ASSET_SIZE) {
172
162
  throw new Error(`Asset size of ${(size / CONVERT_BYTES_TO_MB).toFixed(2)} MB exceeds the maximum allowed size of 200 MB.`);
173
163
  }
174
- const hasNativeModules = detectNativeModules(zip);
175
- if (hasNativeModules?.length > 0) {
176
- const errorMsg = `Native modules detected in Function:\n${hasNativeModules.join('\n')}\n\n` +
177
- `Please replace with JavaScript alternatives.`;
178
- throw new Error(errorMsg);
179
- }
180
164
  const buffer = zip.toBuffer();
181
165
  const b64 = buffer.toString('base64');
182
166
  const hash = hashBuffer(buffer);
@@ -4,7 +4,7 @@ import { setupLogStreaming } from '../../actions/blueprints/logs-streaming.js';
4
4
  import { getStack, updateStack } from '../../actions/blueprints/stacks.js';
5
5
  import { niceId } from '../../utils/display/presenters.js';
6
6
  import { styleText } from '../../utils/style-text.js';
7
- import { isLocalFunctionResource, isStudioResource } from '../../utils/types.js';
7
+ import { isAssetResource } from '../../utils/types.js';
8
8
  const DEFAULT_ASSET_TIMEOUT = 60;
9
9
  const assetTimeoutS = Number(process.env.SANITY_ASSET_TIMEOUT) || DEFAULT_ASSET_TIMEOUT;
10
10
  const assetTimeoutMs = assetTimeoutS * 1000;
@@ -29,18 +29,17 @@ export async function blueprintDeployCore(options) {
29
29
  };
30
30
  }
31
31
  const { resources } = blueprint.parsedBlueprint;
32
- const validResources = resources?.filter((r) => r.type) || [];
33
- const preDeployResources = validResources.filter(isPreDeployResource);
34
- if (preDeployResources.length > 0) {
32
+ const validResources = (resources ?? []).filter((r) => !!r.type);
33
+ const assetResources = validResources.filter(isAssetResource);
34
+ if (assetResources.length > 0) {
35
35
  log('Processing assets...');
36
- for (const resource of preDeployResources) {
36
+ for (const resource of assetResources) {
37
37
  const preDeployResult = await preDeploy(resource, { auth, installer, log });
38
38
  if (!preDeployResult.success)
39
39
  return preDeployResult;
40
40
  const idx = validResources.indexOf(resource);
41
- if (idx !== -1) {
41
+ if (idx !== -1)
42
42
  validResources[idx] = preDeployResult.resource;
43
- }
44
43
  }
45
44
  }
46
45
  const spinner = log.ora('Deploying...').start();
@@ -124,9 +123,6 @@ export async function blueprintDeployCore(options) {
124
123
  return { success: false, error: errorMessage };
125
124
  }
126
125
  }
127
- function isPreDeployResource(r) {
128
- return isLocalFunctionResource(r) || isStudioResource(r);
129
- }
130
126
  async function preDeploy(resource, options) {
131
127
  const { auth, installer, log } = options;
132
128
  const fnSpinner = log.ora({ text: `Processing ${resource.name}...`, prefixText: ' ' }).start();
@@ -2,7 +2,6 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { pathToZip } from '../../actions/blueprints/assets.js';
4
4
  import { findFunctionInBlueprint } from '../../utils/find-function.js';
5
- import { detectNativeModules } from '../../utils/functions/detect-native-modules.js';
6
5
  import { prepareAsset } from '../../utils/functions/prepare-asset.js';
7
6
  import { isLocalFunctionResource } from '../../utils/types.js';
8
7
  export async function functionBuildCore(options) {
@@ -34,10 +33,6 @@ export async function functionBuildCore(options) {
34
33
  continue;
35
34
  }
36
35
  const zip = await pathToZip(prepResult.outputPath);
37
- const nativeModules = detectNativeModules(zip);
38
- if (nativeModules?.length > 0) {
39
- log.warn(`Native modules detected in ${resource.name}: ${nativeModules.join(', ')}`);
40
- }
41
36
  const buffer = zip.toBuffer();
42
37
  const zipPath = path.join(outDir, `${resource.name}.zip`);
43
38
  await fs.promises.writeFile(zipPath, buffer);
@@ -1,4 +1,4 @@
1
- import { isScheduleEvent } from '../../utils/types.js';
1
+ import { isLocalFunctionResource, isScheduleEvent } from '../../utils/types.js';
2
2
  import { styleText } from '../style-text.js';
3
3
  function formatLabel(label) {
4
4
  return styleText('dim', `${label}:`);
@@ -33,11 +33,13 @@ function arrayifyEvent(event) {
33
33
  }
34
34
  export function arrayifyFunction(fn) {
35
35
  const details = [formatLabeledValue('type', fn.type)];
36
- if ('memory' in fn && fn.memory)
36
+ if (!isLocalFunctionResource(fn))
37
+ return details;
38
+ if (fn.memory)
37
39
  details.push(formatLabeledValue('memory', fn.memory));
38
- if ('timeout' in fn && fn.timeout)
40
+ if (fn.timeout)
39
41
  details.push(formatLabeledValue('timeout', fn.timeout));
40
- if ('event' in fn && fn.event) {
42
+ if (fn.event) {
41
43
  const eventDetails = arrayifyEvent(fn.event);
42
44
  if (eventDetails) {
43
45
  details.push(formatLabel('event'));
@@ -1,12 +1,10 @@
1
- import type AdmZip from 'adm-zip';
2
- import type { FunctionResource } from '../types.js';
1
+ import type { Plugin } from 'vite';
2
+ export declare const errorMessage: (elements: string[]) => string;
3
3
  /**
4
- * Recurse node_modules for native modules.
5
- * Native modules built on one platform may not work on another (e.g., macOS vs Linux)
4
+ * Scan the given path. Flag any packages that contain files matching known native module patterns, and return a list of their names.
6
5
  */
7
- export declare const detectNativeModules: (zip: AdmZip) => string[];
6
+ export declare const detectNativeModules: (nodeModules: string) => string[];
8
7
  /**
9
- * Finds the dependencies of the function and compares to the workspace root to see if any native modules are included.
10
- * Due to how PNPM with workspaces symlinks dependencies, we have to check the workspace root for native modules prior to the bundle step.
8
+ * A vite plugin that compares resolved deps of a function against known native module patterns, and throws an error if any are found.
11
9
  */
12
- export declare const detectNativeModulesForBundle: (resource: FunctionResource) => string[];
10
+ export declare const detectNativeModulesPlugin: () => Plugin;
@@ -1,97 +1,105 @@
1
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
1
+ import { existsSync, readdirSync, statSync } from 'node:fs';
2
2
  import path from 'node:path';
3
- import { cwd } from 'node:process';
4
- import { createPnpmRequire } from '../pnpm.js';
5
3
  /**
6
4
  * Patterns to identify native modules based on common file types and build configurations.
7
5
  */
8
6
  const KNOWN_MODULE_PATTERNS = [/binding\.gyp$/, /\.node$/];
7
+ export const errorMessage = (elements) => `Native modules detected:\n${elements.join(`\n`)}\n\n Please replace with JavaScript alternatives`;
9
8
  /**
10
- * Recurse node_modules for native modules.
11
- * Native modules built on one platform may not work on another (e.g., macOS vs Linux)
9
+ * Quick helper so we can recurse through pnpm symlinks if they exist
10
+ * Fallback to statSync if it's a symlink
12
11
  */
13
- export const detectNativeModules = (zip) => {
14
- try {
15
- const zippedEntries = zip.getEntries();
16
- const moduleNames = zippedEntries
17
- // Filter entries that match known native module patterns
18
- .filter((entry) => KNOWN_MODULE_PATTERNS.some((pattern) => pattern.test(entry.entryName)))
19
- // Extract package names from the entry paths
20
- .map((entry) => entry.entryName.match(/node_modules[\\/](.+?)[\\/]/)?.[1])
21
- // Filter out undefined results (in case the regex didn't match)
22
- .filter((name) => name !== undefined);
23
- // return a unique list of module names
24
- return [...new Set(moduleNames)];
25
- }
26
- catch (error) {
27
- const message = error instanceof Error ? error.message : String(error);
28
- throw new Error(`Failed to scan zip for native modules: ${message}`);
29
- }
30
- };
12
+ const isDirEntry = (dir, parent) => dir.isDirectory() || (dir.isSymbolicLink() && statSync(path.join(parent, dir.name)).isDirectory());
31
13
  /**
32
14
  * Recursively checks a directory for files that match known native module patterns.
33
15
  */
34
16
  const hasNativeFiles = (directory) => {
35
- for (const name of readdirSync(directory)) {
17
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
36
18
  // don't recurse back into node_modules.
37
- if (name === 'node_modules')
19
+ if (entry.name === 'node_modules')
38
20
  continue;
39
- const fullPath = path.join(directory, name);
40
- if (statSync(fullPath).isDirectory()) {
41
- if (hasNativeFiles(fullPath))
21
+ const fullPath = path.join(directory, entry.name);
22
+ if (isDirEntry(entry, directory)) {
23
+ if (hasNativeFiles(fullPath)) {
42
24
  return true;
25
+ }
43
26
  }
44
- else if (KNOWN_MODULE_PATTERNS.some((pattern) => pattern.test(name))) {
27
+ else if (KNOWN_MODULE_PATTERNS.some((pattern) => pattern.test(entry.name))) {
45
28
  return true;
46
29
  }
47
30
  }
48
31
  return false;
49
32
  };
50
33
  /**
51
- * Finds the dependencies of the function and compares to the workspace root to see if any native modules are included.
52
- * Due to how PNPM with workspaces symlinks dependencies, we have to check the workspace root for native modules prior to the bundle step.
34
+ * Scan the given path. Flag any packages that contain files matching known native module patterns, and return a list of their names.
53
35
  */
54
- export const detectNativeModulesForBundle = (resource) => {
55
- if (!resource.src)
56
- throw new Error('Resource src is required');
57
- const hasWorkspace = existsSync(path.join(cwd(), 'pnpm-workspace.yaml'));
58
- if (!hasWorkspace) {
59
- return [];
60
- }
61
- const sourcePath = path.resolve(cwd(), resource.src);
62
- const stats = statSync(sourcePath);
63
- const entryDir = stats.isFile() ? path.dirname(sourcePath) : sourcePath;
64
- const hasPackageJson = existsSync(path.join(entryDir, 'package.json'));
65
- // @todo: Can this just move to vite https://linear.app/sanity/issue/RUN-1221/can-we-use-a-vite-plugin-at-transpile-to-determine-native-modules
66
- if (!hasPackageJson) {
67
- // No package.json means we cant run the native module check
68
- // Assuming safe to skip native module detection.
69
- return [];
70
- }
71
- // gets package.json dependencies of the function. We use these function deps to compare against the workspace root modules.
72
- const pkgJsonPath = path.join(entryDir, 'package.json');
73
- // a function should always have deps, but this will just be a little safer.
74
- const functionDeps = JSON.parse(readFileSync(pkgJsonPath, 'utf-8')).dependencies ?? {};
75
- const workspaceModules = createPnpmRequire(cwd());
76
- const nativeModules = [];
77
- for (const depName of Object.keys(functionDeps)) {
78
- try {
79
- const resolved = workspaceModules.resolve(depName);
80
- let currentDir = path.dirname(resolved);
81
- while (currentDir !== cwd() && currentDir !== path.parse(currentDir).root) {
82
- // look for node_module package.json to locate top level
83
- if (existsSync(path.join(currentDir, 'package.json'))) {
84
- if (hasNativeFiles(currentDir)) {
85
- nativeModules.push(depName);
86
- break;
87
- }
88
- }
89
- currentDir = path.dirname(currentDir);
36
+ export const detectNativeModules = (nodeModules) => {
37
+ // because to return the name, we might need to know the scoped package name
38
+ const packages = readdirSync(nodeModules, { withFileTypes: true }).flatMap((entry) => {
39
+ if (entry.name.startsWith('@')) {
40
+ if (!isDirEntry(entry, nodeModules)) {
41
+ return [];
90
42
  }
43
+ const scopePath = path.join(nodeModules, entry.name);
44
+ return readdirSync(scopePath, { withFileTypes: true })
45
+ .filter((pkg) => isDirEntry(pkg, scopePath))
46
+ .map((pkg) => ({
47
+ name: `${entry.name}/${pkg.name}`,
48
+ dir: path.join(scopePath, pkg.name),
49
+ }));
91
50
  }
92
- catch (_e) {
93
- // If we fail to resolve, just skip
51
+ if (!isDirEntry(entry, nodeModules)) {
52
+ return [];
53
+ }
54
+ return [{ name: entry.name, dir: path.join(nodeModules, entry.name) }];
55
+ });
56
+ return packages.filter(({ dir }) => hasNativeFiles(dir)).map(({ name }) => name);
57
+ };
58
+ const findPackageDir = (pathName) => {
59
+ let currentDir = path.dirname(pathName);
60
+ while (currentDir !== path.parse(currentDir).root) {
61
+ // look for node_module package.json to locate top level
62
+ if (existsSync(path.join(currentDir, 'package.json'))) {
63
+ return currentDir;
94
64
  }
65
+ currentDir = path.dirname(currentDir);
95
66
  }
96
- return nativeModules;
67
+ return null;
68
+ };
69
+ /**
70
+ * A vite plugin that compares resolved deps of a function against known native module patterns, and throws an error if any are found.
71
+ */
72
+ export const detectNativeModulesPlugin = () => {
73
+ const flagged = new Set();
74
+ return {
75
+ name: 'detect-native-modules',
76
+ enforce: 'pre',
77
+ async resolveId(source, importer, options) {
78
+ // skip relative imports
79
+ if (source.startsWith('.') || source.startsWith('/') || source.startsWith('\0')) {
80
+ return null;
81
+ }
82
+ const [scope, name] = source.split('/');
83
+ const pkgName = source.startsWith('@') ? `${scope}/${name}` : scope;
84
+ if (!pkgName) {
85
+ return null;
86
+ }
87
+ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });
88
+ if (!resolved)
89
+ return null;
90
+ const pkgDir = findPackageDir(resolved.id);
91
+ if (!pkgDir) {
92
+ return null;
93
+ }
94
+ if (hasNativeFiles(pkgDir)) {
95
+ flagged.add(source);
96
+ }
97
+ return null;
98
+ },
99
+ buildEnd() {
100
+ if (flagged.size > 0) {
101
+ this.error(errorMessage([...flagged]));
102
+ }
103
+ },
104
+ };
97
105
  };
@@ -1,9 +1,10 @@
1
+ import { existsSync } from 'node:fs';
1
2
  import { rm, stat } from 'node:fs/promises';
2
3
  import path from 'node:path';
3
4
  import { cwd } from 'node:process';
4
5
  import { MAX_ASSET_SIZE } from '../../constants.js';
5
6
  import { transpileFunction } from '../transpile/transpile-function.js';
6
- import { detectNativeModulesForBundle } from './detect-native-modules.js';
7
+ import { detectNativeModules, errorMessage } from './detect-native-modules.js';
7
8
  import { getFolderSize } from './getFolderSize.js';
8
9
  import { resolveResourceDependencies } from './resolve-dependencies.js';
9
10
  import { shouldAutoResolveDependencies } from './should-auto-resolve-deps.js';
@@ -17,12 +18,6 @@ export async function prepareAsset({ resource, }, { installer } = {}) {
17
18
  const shouldTranspile = await shouldTranspileFunction(resource);
18
19
  if (shouldTranspile) {
19
20
  try {
20
- const hasNativeModules = detectNativeModulesForBundle(resource);
21
- if (hasNativeModules.length) {
22
- const errorMsg = `Native modules detected:\n${hasNativeModules.join('\n')}\n\n` +
23
- `Please replace with JavaScript alternatives.`;
24
- throw new Error(errorMsg);
25
- }
26
21
  const result = await transpileFunction(resource, { installer });
27
22
  functionPath = result.outputDir;
28
23
  cleanup = result.cleanup;
@@ -37,6 +32,13 @@ export async function prepareAsset({ resource, }, { installer } = {}) {
37
32
  await resolveResourceDependencies(resource, { transpiled: shouldTranspile, installer });
38
33
  await removeArcAutoInstallPackageJson(functionPath);
39
34
  }
35
+ if (existsSync(path.join(functionPath, 'node_modules'))) {
36
+ const modulesPath = path.join(functionPath, 'node_modules');
37
+ const flagged = detectNativeModules(modulesPath);
38
+ if (flagged.length > 0) {
39
+ throw new Error(errorMessage(flagged));
40
+ }
41
+ }
40
42
  try {
41
43
  const size = getFolderSize(functionPath);
42
44
  if (size > MAX_ASSET_SIZE) {
@@ -6,6 +6,7 @@ import { cwd } from 'node:process';
6
6
  import * as find from 'empathic/find';
7
7
  import { build as viteBuild } from 'vite';
8
8
  import tsConfigPaths from 'vite-tsconfig-paths';
9
+ import { detectNativeModulesPlugin } from '../functions/detect-native-modules.js';
9
10
  import { findFunctionEntryPoint } from '../functions/find-entry-point.js';
10
11
  import { createPnpmRequire } from '../pnpm.js';
11
12
  import { cleanupSourceMaps } from './cleanup-source-maps.js';
@@ -68,7 +69,10 @@ export async function transpileFunction(resource, { installer } = {}) {
68
69
  conditions: ['node'],
69
70
  },
70
71
  },
71
- plugins: [tsConfigPaths(), ...(bundle ? [pnpmResolvePlugin(cwd())] : [])],
72
+ plugins: [
73
+ ...(bundle ? [detectNativeModulesPlugin(), pnpmResolvePlugin(cwd())] : []),
74
+ tsConfigPaths(),
75
+ ],
72
76
  });
73
77
  timings['transpile:build'] = performance.now() - viteStart;
74
78
  const verifyStart = performance.now();
@@ -137,6 +141,7 @@ function logCleanupFailure(err) {
137
141
  }
138
142
  /**
139
143
  * Vite plugin to resolve packages from pnpm's virtual store.
144
+ * We don't have a node_modules dir when we bundle with pnpm, so we need a plugin to resolve dependencies from pnpm's virtual store
140
145
  * In pnpm workspaces, hoisted dependencies live in node_modules/.pnpm/node_modules/
141
146
  * which isn't reachable via standard Node resolution.
142
147
  */
@@ -1,5 +1,4 @@
1
1
  import { type BlueprintCorsOriginResource, type BlueprintDatasetResource, type BlueprintDocumentFunctionResource, type BlueprintDocumentWebhookResource, type BlueprintMediaLibraryAssetFunctionResource, type BlueprintProjectResource, type BlueprintResource, type BlueprintRobotResource, type BlueprintRoleResource, type BlueprintScheduledFunctionResource } from '@sanity/blueprints';
2
- import type { Blueprint } from '@sanity/blueprints-parser';
3
2
  export type ScopeType = 'organization' | 'project';
4
3
  /** Result utility type */
5
4
  export type Result<T, E = string> = {
@@ -17,6 +16,12 @@ export interface ActionResponse {
17
16
  /** @internal */
18
17
  export type FunctionGroqResource = BlueprintDocumentFunctionResource | BlueprintMediaLibraryAssetFunctionResource;
19
18
  export type FunctionResource = FunctionGroqResource | BlueprintScheduledFunctionResource;
19
+ export interface StudioResource extends BlueprintResource {
20
+ type: 'sanity.studio';
21
+ src: string;
22
+ }
23
+ /** Resource types that carry a deployable asset (have src: string) */
24
+ export type AssetResource = FunctionResource | StudioResource;
20
25
  /** @internal */
21
26
  export interface AuthParams {
22
27
  token: string;
@@ -41,12 +46,9 @@ export declare function isProjectResource(r: unknown): r is BlueprintProjectReso
41
46
  export declare function isRobotResource(r: unknown): r is BlueprintRobotResource;
42
47
  export declare function isRoleResource(r: unknown): r is BlueprintRoleResource;
43
48
  export declare function isDatasetResource(r: unknown): r is BlueprintDatasetResource;
44
- export declare function isStudioResource(r: unknown): boolean;
49
+ export declare function isStudioResource(r: BlueprintResource): r is StudioResource;
50
+ export declare function isAssetResource(r: BlueprintResource): r is AssetResource;
45
51
  export declare function isWebhookResource(r: unknown): r is BlueprintDocumentWebhookResource;
46
- /** @internal */
47
- export interface CorsResource extends BlueprintResource {
48
- origin?: string;
49
- }
50
52
  interface StackBase {
51
53
  id: string;
52
54
  name: string;
@@ -76,7 +78,9 @@ export interface StackMutation {
76
78
  name: string;
77
79
  scopeType: ScopeType;
78
80
  scopeId: string;
79
- document: Blueprint;
81
+ document: {
82
+ resources?: Array<BlueprintResource & Record<string, unknown>>;
83
+ };
80
84
  }
81
85
  /** @internal */
82
86
  export interface BuildPayloadOptions {
@@ -24,7 +24,10 @@ export function isDatasetResource(r) {
24
24
  }
25
25
  // TODO: update to use blueprints helpers once available
26
26
  export function isStudioResource(r) {
27
- return !!r && typeof r === 'object' && 'type' in r && r.type === 'sanity.studio';
27
+ return r.type === 'sanity.studio';
28
+ }
29
+ export function isAssetResource(r) {
30
+ return isLocalFunctionResource(r) || isStudioResource(r);
28
31
  }
29
32
  export function isWebhookResource(r) {
30
33
  return validateDocumentWebhook(r).length === 0;
@@ -2235,5 +2235,5 @@
2235
2235
  ]
2236
2236
  }
2237
2237
  },
2238
- "version": "14.8.4"
2238
+ "version": "14.8.5"
2239
2239
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sanity/runtime-cli",
3
3
  "description": "Sanity's Runtime CLI for Blueprints and Functions",
4
- "version": "14.8.4",
4
+ "version": "14.8.5",
5
5
  "author": "Sanity Runtime Team",
6
6
  "type": "module",
7
7
  "license": "MIT",