@sanity/cli-core 0.1.0-alpha.14 → 0.1.0-alpha.16
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/_exports/request.d.ts +77 -0
- package/dist/_exports/request.js +7 -0
- package/dist/_exports/request.js.map +1 -0
- package/dist/config/cli/getCliConfig.js +11 -26
- package/dist/config/cli/getCliConfig.js.map +1 -1
- package/dist/config/studio/getStudioWorkspaces.js +7 -0
- package/dist/config/studio/getStudioWorkspaces.js.map +1 -1
- package/dist/config/studio/readStudioConfig.worker.js +6 -5
- package/dist/config/studio/readStudioConfig.worker.js.map +1 -1
- package/dist/index.d.ts +43 -4
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/loaders/studio/studioWorkerLoader.worker.js +101 -22
- package/dist/loaders/studio/studioWorkerLoader.worker.js.map +1 -1
- package/dist/loaders/studio/studioWorkerTask.js +7 -28
- package/dist/loaders/studio/studioWorkerTask.js.map +1 -1
- package/dist/loaders/tsx/tsxWorkerLoader.worker.js +3 -4
- package/dist/loaders/tsx/tsxWorkerLoader.worker.js.map +1 -1
- package/dist/loaders/tsx/tsxWorkerTask.js +4 -32
- package/dist/loaders/tsx/tsxWorkerTask.js.map +1 -1
- package/dist/request/createRequester.js +83 -0
- package/dist/request/createRequester.js.map +1 -0
- package/dist/util/doImport.js +2 -1
- package/dist/util/doImport.js.map +1 -1
- package/dist/util/importModule.js +29 -0
- package/dist/util/importModule.js.map +1 -0
- package/dist/util/promisifyWorker.js +54 -0
- package/dist/util/promisifyWorker.js.map +1 -0
- package/package.json +15 -7
- package/dist/config/cli/getCliConfig.worker.js +0 -15
- package/dist/config/cli/getCliConfig.worker.js.map +0 -1
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import {agent} from 'get-it/middleware'
|
|
2
|
+
import {base} from 'get-it/middleware'
|
|
3
|
+
import {injectResponse} from 'get-it/middleware'
|
|
4
|
+
import {jsonRequest} from 'get-it/middleware'
|
|
5
|
+
import {jsonResponse} from 'get-it/middleware'
|
|
6
|
+
import {keepAlive} from 'get-it/middleware'
|
|
7
|
+
import {observable} from 'get-it/middleware'
|
|
8
|
+
import {progress} from 'get-it/middleware'
|
|
9
|
+
import {proxy} from 'get-it/middleware'
|
|
10
|
+
import {Requester} from 'get-it'
|
|
11
|
+
import {retry} from 'get-it/middleware'
|
|
12
|
+
import {urlEncoded} from 'get-it/middleware'
|
|
13
|
+
|
|
14
|
+
export {agent}
|
|
15
|
+
|
|
16
|
+
export {base}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Creates a `get-it` requester with a standard set of middleware.
|
|
20
|
+
*
|
|
21
|
+
* Default middleware (in order):
|
|
22
|
+
* 1. `httpErrors()` — throw on HTTP error status codes
|
|
23
|
+
* 2. `headers({'User-Agent': '@sanity/cli-core@<version>'})` — identify CLI requests
|
|
24
|
+
* 3. `debug({verbose: true, namespace: 'sanity:cli'})` — debug logging
|
|
25
|
+
* 4. `promise({onlyBody: true})` — return body directly (must be last)
|
|
26
|
+
*
|
|
27
|
+
* @param options - Optional configuration to disable or customize middleware
|
|
28
|
+
* @returns A configured `get-it` requester
|
|
29
|
+
* @public
|
|
30
|
+
*/
|
|
31
|
+
export declare function createRequester(options?: {middleware?: MiddlewareOptions}): Requester
|
|
32
|
+
|
|
33
|
+
export {injectResponse}
|
|
34
|
+
|
|
35
|
+
export {jsonRequest}
|
|
36
|
+
|
|
37
|
+
export {jsonResponse}
|
|
38
|
+
|
|
39
|
+
export {keepAlive}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Options for configuring individual middleware in {@link createRequester}.
|
|
43
|
+
*
|
|
44
|
+
* Each key corresponds to a middleware. Omitting a key uses the default,
|
|
45
|
+
* `false` disables it, and an object merges with the defaults.
|
|
46
|
+
*
|
|
47
|
+
* @public
|
|
48
|
+
*/
|
|
49
|
+
export declare type MiddlewareOptions = {
|
|
50
|
+
debug?:
|
|
51
|
+
| false
|
|
52
|
+
| {
|
|
53
|
+
namespace?: string
|
|
54
|
+
verbose?: boolean
|
|
55
|
+
}
|
|
56
|
+
headers?: false | Record<string, string>
|
|
57
|
+
httpErrors?: false
|
|
58
|
+
promise?:
|
|
59
|
+
| false
|
|
60
|
+
| {
|
|
61
|
+
onlyBody?: boolean
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export {observable}
|
|
66
|
+
|
|
67
|
+
export {progress}
|
|
68
|
+
|
|
69
|
+
export {proxy}
|
|
70
|
+
|
|
71
|
+
export {Requester}
|
|
72
|
+
|
|
73
|
+
export {retry}
|
|
74
|
+
|
|
75
|
+
export {urlEncoded}
|
|
76
|
+
|
|
77
|
+
export {}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { createRequester } from '../request/createRequester.js';
|
|
2
|
+
// Re-export non-default middleware from get-it for use alongside createRequester.
|
|
3
|
+
// Default middleware (httpErrors, headers, debug, promise) are applied automatically
|
|
4
|
+
// by createRequester and don't need to be imported separately.
|
|
5
|
+
export { agent, base, injectResponse, jsonRequest, jsonResponse, keepAlive, observable, progress, proxy, retry, urlEncoded } from 'get-it/middleware';
|
|
6
|
+
|
|
7
|
+
//# sourceMappingURL=request.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/_exports/request.ts"],"sourcesContent":["export {createRequester, type MiddlewareOptions} from '../request/createRequester.js'\n\n// Re-export get-it types used by consumers of createRequester\nexport {type Requester} from 'get-it'\n\n// Re-export non-default middleware from get-it for use alongside createRequester.\n// Default middleware (httpErrors, headers, debug, promise) are applied automatically\n// by createRequester and don't need to be imported separately.\nexport {\n agent,\n base,\n injectResponse,\n jsonRequest,\n jsonResponse,\n keepAlive,\n observable,\n progress,\n proxy,\n retry,\n urlEncoded,\n} from 'get-it/middleware'\n"],"names":["createRequester","agent","base","injectResponse","jsonRequest","jsonResponse","keepAlive","observable","progress","proxy","retry","urlEncoded"],"mappings":"AAAA,SAAQA,eAAe,QAA+B,gCAA+B;AAKrF,kFAAkF;AAClF,qFAAqF;AACrF,+DAA+D;AAC/D,SACEC,KAAK,EACLC,IAAI,EACJC,cAAc,EACdC,WAAW,EACXC,YAAY,EACZC,SAAS,EACTC,UAAU,EACVC,QAAQ,EACRC,KAAK,EACLC,KAAK,EACLC,UAAU,QACL,oBAAmB"}
|
|
@@ -1,10 +1,6 @@
|
|
|
1
|
-
import { pathToFileURL } from 'node:url';
|
|
2
|
-
import { getTsconfig } from 'get-tsconfig';
|
|
3
|
-
import { tsImport } from 'tsx/esm/api';
|
|
4
1
|
import { debug } from '../../debug.js';
|
|
5
|
-
import {
|
|
2
|
+
import { importModule } from '../../util/importModule.js';
|
|
6
3
|
import { NotFoundError } from '../../util/NotFoundError.js';
|
|
7
|
-
import { tryGetDefaultExport } from '../../util/tryGetDefaultExport.js';
|
|
8
4
|
import { findPathForFiles } from '../util/findConfigsPaths.js';
|
|
9
5
|
import { cliConfigSchema } from './schemas.js';
|
|
10
6
|
/**
|
|
@@ -33,36 +29,25 @@ import { cliConfigSchema } from './schemas.js';
|
|
|
33
29
|
throw new Error(`Multiple CLI config files found (${configPaths.map((path)=>path.path).join(', ')})`);
|
|
34
30
|
}
|
|
35
31
|
const configPath = configPaths[0].path;
|
|
32
|
+
debug(`Loading CLI config from: ${configPath}`);
|
|
36
33
|
let cliConfig;
|
|
37
34
|
try {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
workerData: {
|
|
42
|
-
configPath
|
|
43
|
-
}
|
|
44
|
-
});
|
|
35
|
+
const result = await importModule(configPath);
|
|
36
|
+
debug('CLI config loaded: %o', result);
|
|
37
|
+
cliConfig = result;
|
|
45
38
|
} catch (err) {
|
|
46
39
|
debug('Failed to load CLI config in worker thread: %s', err);
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const tsconfig = getTsconfig(rootPath);
|
|
50
|
-
// Ensure we get the default export (sometimes we get a bit of a mixed bag)
|
|
51
|
-
cliConfig = await tsImport(pathToFileURL(configPath).href, {
|
|
52
|
-
parentURL: import.meta.url,
|
|
53
|
-
tsconfig: tsconfig?.path ?? undefined
|
|
40
|
+
throw new Error('CLI config cannot be loaded', {
|
|
41
|
+
cause: err
|
|
54
42
|
});
|
|
55
|
-
cliConfig = tryGetDefaultExport(cliConfig);
|
|
56
|
-
if (!cliConfig) {
|
|
57
|
-
throw new Error('Invalid CLI config structure');
|
|
58
|
-
}
|
|
59
43
|
}
|
|
60
44
|
const { data, error, success } = cliConfigSchema.safeParse(cliConfig);
|
|
61
45
|
if (!success) {
|
|
62
|
-
|
|
46
|
+
debug(`Invalid CLI config: ${error.message}`);
|
|
47
|
+
throw new Error(`Invalid CLI config: ${error.message}`, {
|
|
48
|
+
cause: error
|
|
49
|
+
});
|
|
63
50
|
}
|
|
64
|
-
// There is a minor difference here because of the `vite` property and how the types
|
|
65
|
-
// aren't as specific as our manually typed `CliConfig` type, thus the cast.
|
|
66
51
|
return data;
|
|
67
52
|
}
|
|
68
53
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/cli/getCliConfig.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../src/config/cli/getCliConfig.ts"],"sourcesContent":["import {debug} from '../../debug.js'\nimport {importModule} from '../../util/importModule.js'\nimport {NotFoundError} from '../../util/NotFoundError.js'\nimport {findPathForFiles} from '../util/findConfigsPaths.js'\nimport {cliConfigSchema} from './schemas.js'\nimport {type CliConfig} from './types/cliConfig.js'\n\n/**\n * Get the CLI config for a project, given the root path.\n *\n * We really want to avoid loading the CLI config in the main thread, as we'll need\n * TypeScript loading logic, potentially with ts path aliases, syntax extensions and all\n * sorts of nonsense. Thus, we _attempt_ to use a worker thread - but have to fall back\n * to using the main thread if not possible. This can be the case if the configuration\n * contains non-serializable properties, such as functions. This is unfortunately used\n * by the vite config, for example.\n *\n * @param rootPath - Root path for the project, eg where `sanity.cli.(ts|js)` is located.\n * @returns The CLI config\n * @internal\n */\nexport async function getCliConfig(rootPath: string): Promise<CliConfig> {\n const paths = await findPathForFiles(rootPath, ['sanity.cli.ts', 'sanity.cli.js'])\n const configPaths = paths.filter((path) => path.exists)\n\n if (configPaths.length === 0) {\n throw new NotFoundError(`No CLI config found at ${rootPath}/sanity.cli.(ts|js)`)\n }\n\n if (configPaths.length > 1) {\n throw new Error(\n `Multiple CLI config files found (${configPaths.map((path) => path.path).join(', ')})`,\n )\n }\n\n const configPath = configPaths[0].path\n\n debug(`Loading CLI config from: ${configPath}`)\n\n let cliConfig: CliConfig | undefined\n try {\n const result = await importModule<CliConfig>(configPath)\n\n debug('CLI config loaded: %o', result)\n\n cliConfig = result\n } catch (err) {\n debug('Failed to load CLI config in worker thread: %s', err)\n\n throw new Error('CLI config cannot be loaded', {cause: err})\n }\n\n const {data, error, success} = cliConfigSchema.safeParse(cliConfig)\n if (!success) {\n debug(`Invalid CLI config: ${error.message}`)\n throw new Error(`Invalid CLI config: ${error.message}`, {cause: error})\n }\n\n return data\n}\n"],"names":["debug","importModule","NotFoundError","findPathForFiles","cliConfigSchema","getCliConfig","rootPath","paths","configPaths","filter","path","exists","length","Error","map","join","configPath","cliConfig","result","err","cause","data","error","success","safeParse","message"],"mappings":"AAAA,SAAQA,KAAK,QAAO,iBAAgB;AACpC,SAAQC,YAAY,QAAO,6BAA4B;AACvD,SAAQC,aAAa,QAAO,8BAA6B;AACzD,SAAQC,gBAAgB,QAAO,8BAA6B;AAC5D,SAAQC,eAAe,QAAO,eAAc;AAG5C;;;;;;;;;;;;;CAaC,GACD,OAAO,eAAeC,aAAaC,QAAgB;IACjD,MAAMC,QAAQ,MAAMJ,iBAAiBG,UAAU;QAAC;QAAiB;KAAgB;IACjF,MAAME,cAAcD,MAAME,MAAM,CAAC,CAACC,OAASA,KAAKC,MAAM;IAEtD,IAAIH,YAAYI,MAAM,KAAK,GAAG;QAC5B,MAAM,IAAIV,cAAc,CAAC,uBAAuB,EAAEI,SAAS,mBAAmB,CAAC;IACjF;IAEA,IAAIE,YAAYI,MAAM,GAAG,GAAG;QAC1B,MAAM,IAAIC,MACR,CAAC,iCAAiC,EAAEL,YAAYM,GAAG,CAAC,CAACJ,OAASA,KAAKA,IAAI,EAAEK,IAAI,CAAC,MAAM,CAAC,CAAC;IAE1F;IAEA,MAAMC,aAAaR,WAAW,CAAC,EAAE,CAACE,IAAI;IAEtCV,MAAM,CAAC,yBAAyB,EAAEgB,YAAY;IAE9C,IAAIC;IACJ,IAAI;QACF,MAAMC,SAAS,MAAMjB,aAAwBe;QAE7ChB,MAAM,yBAAyBkB;QAE/BD,YAAYC;IACd,EAAE,OAAOC,KAAK;QACZnB,MAAM,kDAAkDmB;QAExD,MAAM,IAAIN,MAAM,+BAA+B;YAACO,OAAOD;QAAG;IAC5D;IAEA,MAAM,EAACE,IAAI,EAAEC,KAAK,EAAEC,OAAO,EAAC,GAAGnB,gBAAgBoB,SAAS,CAACP;IACzD,IAAI,CAACM,SAAS;QACZvB,MAAM,CAAC,oBAAoB,EAAEsB,MAAMG,OAAO,EAAE;QAC5C,MAAM,IAAIZ,MAAM,CAAC,oBAAoB,EAAES,MAAMG,OAAO,EAAE,EAAE;YAACL,OAAOE;QAAK;IACvE;IAEA,OAAOD;AACT"}
|
|
@@ -2,11 +2,13 @@ import { stat } from 'node:fs/promises';
|
|
|
2
2
|
import { dirname } from 'node:path';
|
|
3
3
|
import { isMainThread } from 'node:worker_threads';
|
|
4
4
|
import { firstValueFrom, of } from 'rxjs';
|
|
5
|
+
import { subdebug } from '../../debug.js';
|
|
5
6
|
import { doImport } from '../../util/doImport.js';
|
|
6
7
|
import { getEmptyAuth } from '../../util/getEmptyAuth.js';
|
|
7
8
|
import { resolveLocalPackage } from '../../util/resolveLocalPackage.js';
|
|
8
9
|
import { findStudioConfigPath } from '../util/findStudioConfigPath.js';
|
|
9
10
|
import { isStudioConfig } from './isStudioConfig.js';
|
|
11
|
+
const debug = subdebug('worker:getStudioWorkspaces');
|
|
10
12
|
/**
|
|
11
13
|
* Resolves the workspaces from the studio config.
|
|
12
14
|
*
|
|
@@ -23,14 +25,18 @@ import { isStudioConfig } from './isStudioConfig.js';
|
|
|
23
25
|
if (isDirectory) {
|
|
24
26
|
configPath = await findStudioConfigPath(configPath);
|
|
25
27
|
}
|
|
28
|
+
debug('Finding studio config path %s', configPath);
|
|
26
29
|
let config = await doImport(configPath);
|
|
30
|
+
debug('Imported config %o', config);
|
|
27
31
|
if (!isStudioConfig(config)) {
|
|
28
32
|
if (!('default' in config) || !isStudioConfig(config.default)) {
|
|
33
|
+
debug('Invalid studio config format in "%s"', configPath);
|
|
29
34
|
throw new TypeError(`Invalid studio config format in "${configPath}"`);
|
|
30
35
|
}
|
|
31
36
|
config = config.default;
|
|
32
37
|
}
|
|
33
38
|
const workDir = dirname(configPath);
|
|
39
|
+
debug('Work dir %s', workDir);
|
|
34
40
|
const { resolveConfig } = await resolveLocalPackage('sanity', workDir);
|
|
35
41
|
if (typeof resolveConfig !== 'function') {
|
|
36
42
|
throw new TypeError('Expected `resolveConfig` from `sanity` to be a function');
|
|
@@ -50,6 +56,7 @@ import { isStudioConfig } from './isStudioConfig.js';
|
|
|
50
56
|
state: of(getEmptyAuth())
|
|
51
57
|
}
|
|
52
58
|
}));
|
|
59
|
+
debug('Unauthed workspaces %o', unauthedWorkspaces);
|
|
53
60
|
return firstValueFrom(resolveConfig(unauthedWorkspaces));
|
|
54
61
|
}
|
|
55
62
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/studio/getStudioWorkspaces.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {dirname} from 'node:path'\nimport {isMainThread} from 'node:worker_threads'\n\nimport {firstValueFrom, of} from 'rxjs'\nimport {type Workspace} from 'sanity'\n\nimport {doImport} from '../../util/doImport.js'\nimport {getEmptyAuth} from '../../util/getEmptyAuth.js'\nimport {resolveLocalPackage} from '../../util/resolveLocalPackage.js'\nimport {findStudioConfigPath} from '../util/findStudioConfigPath.js'\nimport {isStudioConfig} from './isStudioConfig.js'\n\n/**\n * Resolves the workspaces from the studio config.\n *\n * NOTE: This function should only be called from a worker thread.\n *\n * @param configPath - The path to the studio config\n * @returns The workspaces\n * @internal\n */\nexport async function getStudioWorkspaces(configPath: string): Promise<Workspace[]> {\n if (isMainThread) {\n throw new Error('getStudioWorkspaces should only be called from a worker thread')\n }\n const isDirectory = (await stat(configPath)).isDirectory()\n if (isDirectory) {\n configPath = await findStudioConfigPath(configPath)\n }\n let config = await doImport(configPath)\n if (!isStudioConfig(config)) {\n if (!('default' in config) || !isStudioConfig(config.default)) {\n throw new TypeError(`Invalid studio config format in \"${configPath}\"`)\n }\n\n config = config.default\n }\n\n const workDir = dirname(configPath)\n const {resolveConfig} = await resolveLocalPackage<typeof import('sanity')>('sanity', workDir)\n if (typeof resolveConfig !== 'function') {\n throw new TypeError('Expected `resolveConfig` from `sanity` to be a function')\n }\n\n // We will also want to stub out some configuration - we don't need to resolve the\n // users' logged in state, for instance - so let's disable the auth implementation.\n const rawWorkspaces = Array.isArray(config)\n ? config\n : [{...config, basePath: config.basePath || '/', name: config.name || 'default'}]\n\n const unauthedWorkspaces = rawWorkspaces.map((workspace) => ({\n ...workspace,\n auth: {state: of(getEmptyAuth())},\n }))\n\n return firstValueFrom(resolveConfig(unauthedWorkspaces))\n}\n"],"names":["stat","dirname","isMainThread","firstValueFrom","of","doImport","getEmptyAuth","resolveLocalPackage","findStudioConfigPath","isStudioConfig","getStudioWorkspaces","configPath","Error","isDirectory","config","default","TypeError","workDir","resolveConfig","rawWorkspaces","Array","isArray","basePath","name","unauthedWorkspaces","map","workspace","auth","state"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,OAAO,QAAO,YAAW;AACjC,SAAQC,YAAY,QAAO,sBAAqB;AAEhD,SAAQC,cAAc,EAAEC,EAAE,QAAO,OAAM;AAGvC,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,YAAY,QAAO,6BAA4B;AACvD,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,oBAAoB,QAAO,kCAAiC;AACpE,SAAQC,cAAc,QAAO,sBAAqB;AAElD;;;;;;;;CAQC,GACD,OAAO,
|
|
1
|
+
{"version":3,"sources":["../../../src/config/studio/getStudioWorkspaces.ts"],"sourcesContent":["import {stat} from 'node:fs/promises'\nimport {dirname} from 'node:path'\nimport {isMainThread} from 'node:worker_threads'\n\nimport {firstValueFrom, of} from 'rxjs'\nimport {type Workspace} from 'sanity'\n\nimport {subdebug} from '../../debug.js'\nimport {doImport} from '../../util/doImport.js'\nimport {getEmptyAuth} from '../../util/getEmptyAuth.js'\nimport {resolveLocalPackage} from '../../util/resolveLocalPackage.js'\nimport {findStudioConfigPath} from '../util/findStudioConfigPath.js'\nimport {isStudioConfig} from './isStudioConfig.js'\n\nconst debug = subdebug('worker:getStudioWorkspaces')\n\n/**\n * Resolves the workspaces from the studio config.\n *\n * NOTE: This function should only be called from a worker thread.\n *\n * @param configPath - The path to the studio config\n * @returns The workspaces\n * @internal\n */\nexport async function getStudioWorkspaces(configPath: string): Promise<Workspace[]> {\n if (isMainThread) {\n throw new Error('getStudioWorkspaces should only be called from a worker thread')\n }\n const isDirectory = (await stat(configPath)).isDirectory()\n if (isDirectory) {\n configPath = await findStudioConfigPath(configPath)\n }\n debug('Finding studio config path %s', configPath)\n let config = await doImport(configPath)\n\n debug('Imported config %o', config)\n if (!isStudioConfig(config)) {\n if (!('default' in config) || !isStudioConfig(config.default)) {\n debug('Invalid studio config format in \"%s\"', configPath)\n throw new TypeError(`Invalid studio config format in \"${configPath}\"`)\n }\n\n config = config.default\n }\n\n const workDir = dirname(configPath)\n debug('Work dir %s', workDir)\n const {resolveConfig} = await resolveLocalPackage<typeof import('sanity')>('sanity', workDir)\n if (typeof resolveConfig !== 'function') {\n throw new TypeError('Expected `resolveConfig` from `sanity` to be a function')\n }\n\n // We will also want to stub out some configuration - we don't need to resolve the\n // users' logged in state, for instance - so let's disable the auth implementation.\n const rawWorkspaces = Array.isArray(config)\n ? config\n : [{...config, basePath: config.basePath || '/', name: config.name || 'default'}]\n\n const unauthedWorkspaces = rawWorkspaces.map((workspace) => ({\n ...workspace,\n auth: {state: of(getEmptyAuth())},\n }))\n\n debug('Unauthed workspaces %o', unauthedWorkspaces)\n\n return firstValueFrom(resolveConfig(unauthedWorkspaces))\n}\n"],"names":["stat","dirname","isMainThread","firstValueFrom","of","subdebug","doImport","getEmptyAuth","resolveLocalPackage","findStudioConfigPath","isStudioConfig","debug","getStudioWorkspaces","configPath","Error","isDirectory","config","default","TypeError","workDir","resolveConfig","rawWorkspaces","Array","isArray","basePath","name","unauthedWorkspaces","map","workspace","auth","state"],"mappings":"AAAA,SAAQA,IAAI,QAAO,mBAAkB;AACrC,SAAQC,OAAO,QAAO,YAAW;AACjC,SAAQC,YAAY,QAAO,sBAAqB;AAEhD,SAAQC,cAAc,EAAEC,EAAE,QAAO,OAAM;AAGvC,SAAQC,QAAQ,QAAO,iBAAgB;AACvC,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,YAAY,QAAO,6BAA4B;AACvD,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,oBAAoB,QAAO,kCAAiC;AACpE,SAAQC,cAAc,QAAO,sBAAqB;AAElD,MAAMC,QAAQN,SAAS;AAEvB;;;;;;;;CAQC,GACD,OAAO,eAAeO,oBAAoBC,UAAkB;IAC1D,IAAIX,cAAc;QAChB,MAAM,IAAIY,MAAM;IAClB;IACA,MAAMC,cAAc,AAAC,CAAA,MAAMf,KAAKa,WAAU,EAAGE,WAAW;IACxD,IAAIA,aAAa;QACfF,aAAa,MAAMJ,qBAAqBI;IAC1C;IACAF,MAAM,iCAAiCE;IACvC,IAAIG,SAAS,MAAMV,SAASO;IAE5BF,MAAM,sBAAsBK;IAC5B,IAAI,CAACN,eAAeM,SAAS;QAC3B,IAAI,CAAE,CAAA,aAAaA,MAAK,KAAM,CAACN,eAAeM,OAAOC,OAAO,GAAG;YAC7DN,MAAM,wCAAwCE;YAC9C,MAAM,IAAIK,UAAU,CAAC,iCAAiC,EAAEL,WAAW,CAAC,CAAC;QACvE;QAEAG,SAASA,OAAOC,OAAO;IACzB;IAEA,MAAME,UAAUlB,QAAQY;IACxBF,MAAM,eAAeQ;IACrB,MAAM,EAACC,aAAa,EAAC,GAAG,MAAMZ,oBAA6C,UAAUW;IACrF,IAAI,OAAOC,kBAAkB,YAAY;QACvC,MAAM,IAAIF,UAAU;IACtB;IAEA,kFAAkF;IAClF,mFAAmF;IACnF,MAAMG,gBAAgBC,MAAMC,OAAO,CAACP,UAChCA,SACA;QAAC;YAAC,GAAGA,MAAM;YAAEQ,UAAUR,OAAOQ,QAAQ,IAAI;YAAKC,MAAMT,OAAOS,IAAI,IAAI;QAAS;KAAE;IAEnF,MAAMC,qBAAqBL,cAAcM,GAAG,CAAC,CAACC,YAAe,CAAA;YAC3D,GAAGA,SAAS;YACZC,MAAM;gBAACC,OAAO1B,GAAGG;YAAe;QAClC,CAAA;IAEAI,MAAM,0BAA0Be;IAEhC,OAAOvB,eAAeiB,cAAcM;AACtC"}
|
|
@@ -1,24 +1,25 @@
|
|
|
1
1
|
import { isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
+
import { subdebug } from '../../debug.js';
|
|
3
4
|
import { doImport } from '../../util/doImport.js';
|
|
4
5
|
import { safeStructuredClone } from '../../util/safeStructuredClone.js';
|
|
5
6
|
import { getStudioWorkspaces } from './getStudioWorkspaces.js';
|
|
6
7
|
if (isMainThread || !parentPort) {
|
|
7
8
|
throw new Error('Should only be run in a worker!');
|
|
8
9
|
}
|
|
10
|
+
const debug = subdebug('readStudioConfig.worker');
|
|
9
11
|
const { configPath, resolvePlugins } = z.object({
|
|
10
12
|
configPath: z.string(),
|
|
11
13
|
resolvePlugins: z.boolean()
|
|
12
14
|
}).parse(workerData);
|
|
15
|
+
debug('Parsing config path %s', configPath);
|
|
13
16
|
let { default: config } = await doImport(configPath);
|
|
17
|
+
debug('Imported config %o', config);
|
|
14
18
|
if (resolvePlugins) {
|
|
19
|
+
debug('Resolving workspaces');
|
|
15
20
|
config = await getStudioWorkspaces(configPath);
|
|
21
|
+
debug('Resolved workspaces %o', config);
|
|
16
22
|
}
|
|
17
23
|
parentPort.postMessage(safeStructuredClone(config));
|
|
18
|
-
// Explicitly exit the process to avoid any dangling references from keeping
|
|
19
|
-
// the process alive after resolving it's main task
|
|
20
|
-
setImmediate(()=>{
|
|
21
|
-
process.exit(1);
|
|
22
|
-
});
|
|
23
24
|
|
|
24
25
|
//# sourceMappingURL=readStudioConfig.worker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/studio/readStudioConfig.worker.ts"],"sourcesContent":["import {isMainThread, parentPort, workerData} from 'node:worker_threads'\n\nimport {z} from 'zod'\n\nimport {doImport} from '../../util/doImport.js'\nimport {safeStructuredClone} from '../../util/safeStructuredClone.js'\nimport {getStudioWorkspaces} from './getStudioWorkspaces.js'\n\nif (isMainThread || !parentPort) {\n throw new Error('Should only be run in a worker!')\n}\n\nconst {configPath, resolvePlugins} = z\n .object({configPath: z.string(), resolvePlugins: z.boolean()})\n .parse(workerData)\n\nlet {default: config} = await doImport(configPath)\n\nif (resolvePlugins) {\n config = await getStudioWorkspaces(configPath)\n}\n\nparentPort.postMessage(safeStructuredClone(config))\n
|
|
1
|
+
{"version":3,"sources":["../../../src/config/studio/readStudioConfig.worker.ts"],"sourcesContent":["import {isMainThread, parentPort, workerData} from 'node:worker_threads'\n\nimport {z} from 'zod'\n\nimport {subdebug} from '../../debug.js'\nimport {doImport} from '../../util/doImport.js'\nimport {safeStructuredClone} from '../../util/safeStructuredClone.js'\nimport {getStudioWorkspaces} from './getStudioWorkspaces.js'\n\nif (isMainThread || !parentPort) {\n throw new Error('Should only be run in a worker!')\n}\n\nconst debug = subdebug('readStudioConfig.worker')\n\nconst {configPath, resolvePlugins} = z\n .object({configPath: z.string(), resolvePlugins: z.boolean()})\n .parse(workerData)\n\ndebug('Parsing config path %s', configPath)\n\nlet {default: config} = await doImport(configPath)\n\ndebug('Imported config %o', config)\n\nif (resolvePlugins) {\n debug('Resolving workspaces')\n config = await getStudioWorkspaces(configPath)\n debug('Resolved workspaces %o', config)\n}\n\nparentPort.postMessage(safeStructuredClone(config))\n"],"names":["isMainThread","parentPort","workerData","z","subdebug","doImport","safeStructuredClone","getStudioWorkspaces","Error","debug","configPath","resolvePlugins","object","string","boolean","parse","default","config","postMessage"],"mappings":"AAAA,SAAQA,YAAY,EAAEC,UAAU,EAAEC,UAAU,QAAO,sBAAqB;AAExE,SAAQC,CAAC,QAAO,MAAK;AAErB,SAAQC,QAAQ,QAAO,iBAAgB;AACvC,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,mBAAmB,QAAO,oCAAmC;AACrE,SAAQC,mBAAmB,QAAO,2BAA0B;AAE5D,IAAIP,gBAAgB,CAACC,YAAY;IAC/B,MAAM,IAAIO,MAAM;AAClB;AAEA,MAAMC,QAAQL,SAAS;AAEvB,MAAM,EAACM,UAAU,EAAEC,cAAc,EAAC,GAAGR,EAClCS,MAAM,CAAC;IAACF,YAAYP,EAAEU,MAAM;IAAIF,gBAAgBR,EAAEW,OAAO;AAAE,GAC3DC,KAAK,CAACb;AAETO,MAAM,0BAA0BC;AAEhC,IAAI,EAACM,SAASC,MAAM,EAAC,GAAG,MAAMZ,SAASK;AAEvCD,MAAM,sBAAsBQ;AAE5B,IAAIN,gBAAgB;IAClBF,MAAM;IACNQ,SAAS,MAAMV,oBAAoBG;IACnCD,MAAM,0BAA0BQ;AAClC;AAEAhB,WAAWiB,WAAW,CAACZ,oBAAoBW"}
|
package/dist/index.d.ts
CHANGED
|
@@ -8,8 +8,7 @@ import debugIt from 'debug'
|
|
|
8
8
|
import {InlineConfig} from 'vite'
|
|
9
9
|
import {Interfaces} from '@oclif/core'
|
|
10
10
|
import {PluginOptions} from 'babel-plugin-react-compiler'
|
|
11
|
-
import {SanityClient} from 'sanity'
|
|
12
|
-
import {SanityClient as SanityClient_2} from '@sanity/client'
|
|
11
|
+
import {SanityClient} from '@sanity/client'
|
|
13
12
|
import {TelemetryEvent} from '@sanity/telemetry'
|
|
14
13
|
import {TelemetryLogger} from '@sanity/telemetry'
|
|
15
14
|
import {URL as URL_2} from 'node:url'
|
|
@@ -504,7 +503,7 @@ export declare function getGlobalCliClient({
|
|
|
504
503
|
requireUser,
|
|
505
504
|
token: providedToken,
|
|
506
505
|
...config
|
|
507
|
-
}: GlobalCliClientOptions): Promise<
|
|
506
|
+
}: GlobalCliClientOptions): Promise<SanityClient>
|
|
508
507
|
|
|
509
508
|
/**
|
|
510
509
|
* Create a "project" (scoped) Sanity API client.
|
|
@@ -518,7 +517,7 @@ export declare function getProjectCliClient({
|
|
|
518
517
|
requireUser,
|
|
519
518
|
token: providedToken,
|
|
520
519
|
...config
|
|
521
|
-
}: ProjectCliClientOptions): Promise<
|
|
520
|
+
}: ProjectCliClientOptions): Promise<SanityClient>
|
|
522
521
|
|
|
523
522
|
/**
|
|
524
523
|
* Gets an environment variable with the appropriate Sanity prefix based on whether it's an app or studio.
|
|
@@ -616,6 +615,33 @@ export declare interface GlobalCliClientOptions extends ClientConfig {
|
|
|
616
615
|
requireUser?: boolean
|
|
617
616
|
}
|
|
618
617
|
|
|
618
|
+
/**
|
|
619
|
+
* Imports a module using jiti and returns its exports.
|
|
620
|
+
* This is a thin wrapper around tsx to allow swapping out the underlying implementation in the future if needed.
|
|
621
|
+
*
|
|
622
|
+
* @param filePath - Path to the module to import.
|
|
623
|
+
* @param options - Options for the importModule function.
|
|
624
|
+
* @returns The exported module.
|
|
625
|
+
*
|
|
626
|
+
* @internal
|
|
627
|
+
*/
|
|
628
|
+
export declare function importModule<T = unknown>(
|
|
629
|
+
filePath: string | URL,
|
|
630
|
+
options?: ImportModuleOptions,
|
|
631
|
+
): Promise<T>
|
|
632
|
+
|
|
633
|
+
declare interface ImportModuleOptions {
|
|
634
|
+
/**
|
|
635
|
+
* Whether to return the default export of the module.
|
|
636
|
+
*/
|
|
637
|
+
default?: true
|
|
638
|
+
/**
|
|
639
|
+
* Path to the tsconfig file to use for the import. If not provided, the tsconfig
|
|
640
|
+
* will be inferred from the nearest `tsconfig.json` file.
|
|
641
|
+
*/
|
|
642
|
+
tsconfigPath?: string
|
|
643
|
+
}
|
|
644
|
+
|
|
619
645
|
export declare const isCi: () => boolean
|
|
620
646
|
|
|
621
647
|
export declare function isInteractive(): boolean
|
|
@@ -782,6 +808,19 @@ export declare interface ProjectRootResult {
|
|
|
782
808
|
type: 'app' | 'studio'
|
|
783
809
|
}
|
|
784
810
|
|
|
811
|
+
/**
|
|
812
|
+
* Wraps a Node.js Worker in a Promise that resolves with the first message
|
|
813
|
+
* the worker sends, and rejects on error, message deserialization failure,
|
|
814
|
+
* or non-zero exit code. The worker is terminated after a message or error
|
|
815
|
+
* is received.
|
|
816
|
+
*
|
|
817
|
+
* @param worker - The Worker instance to promisify
|
|
818
|
+
* @returns A promise that resolves with the first message from the worker
|
|
819
|
+
* @throws If the worker emits an error, a message deserialization error, or exits with a non-zero code
|
|
820
|
+
* @internal
|
|
821
|
+
*/
|
|
822
|
+
export declare function promisifyWorker<T = unknown>(worker: Worker_2): Promise<T>
|
|
823
|
+
|
|
785
824
|
declare const rawConfigSchema: z_2.ZodUnion<
|
|
786
825
|
readonly [
|
|
787
826
|
z_2.ZodArray<
|
package/dist/index.js
CHANGED
|
@@ -26,6 +26,7 @@ export * from './util/getEmptyAuth.js';
|
|
|
26
26
|
export * from './util/getSanityEnvVar.js';
|
|
27
27
|
export * from './util/getSanityUrl.js';
|
|
28
28
|
export * from './util/getUserConfig.js';
|
|
29
|
+
export * from './util/importModule.js';
|
|
29
30
|
export * from './util/isCi.js';
|
|
30
31
|
export * from './util/isInteractive.js';
|
|
31
32
|
export * from './util/isRecord.js';
|
|
@@ -33,6 +34,7 @@ export * from './util/isStaging.js';
|
|
|
33
34
|
export * from './util/isTrueish.js';
|
|
34
35
|
export * from './util/normalizePath.js';
|
|
35
36
|
export * from './util/parseStringFlag.js';
|
|
37
|
+
export * from './util/promisifyWorker.js';
|
|
36
38
|
export * from './util/readNDJSON.js';
|
|
37
39
|
export * from './util/readPackageJson.js';
|
|
38
40
|
export * from './util/resolveLocalPackage.js';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './config/cli/getCliConfig.js'\nexport * from './config/cli/getCliConfigSync.js'\nexport {type CliConfig} from './config/cli/types/cliConfig.js'\nexport {type UserViteConfig} from './config/cli/types/userViteConfig.js'\nexport * from './config/findProjectRoot.js'\nexport * from './config/findProjectRootSync.js'\nexport * from './config/studio/getStudioConfig.js'\nexport * from './config/studio/getStudioWorkspaces.js'\nexport * from './config/util/findConfigsPaths.js'\nexport * from './config/util/findStudioConfigPath.js'\nexport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nexport * from './debug.js'\nexport * from './loaders/studio/studioWorkerTask.js'\nexport * from './loaders/tsx/tsxWorkerTask.js'\nexport * from './SanityCommand.js'\nexport * from './services/apiClient.js'\nexport * from './services/cliUserConfig.js'\nexport * from './services/getCliToken.js'\nexport * from './telemetry/createTelemetryStore.js'\nexport * from './telemetry/flushTelemetryFiles.js'\nexport * from './telemetry/getTelemetryBaseInfo.js'\nexport * from './telemetry/telemetryStoreDebug.js'\nexport {\n type CLITelemetryStore,\n type ConsentInformation,\n type TelemetryUserProperties,\n} from './telemetry/types.js'\nexport {type Output, type SanityOrgUser} from './types.js'\nexport * from './util/createExpiringConfig.js'\nexport {doImport} from './util/doImport.js'\nexport * from './util/environment/mockBrowserEnvironment.js'\nexport * from './util/fileExists.js'\nexport {\n clearCliTelemetry,\n CLI_TELEMETRY_SYMBOL,\n getCliTelemetry,\n setCliTelemetry,\n} from './util/getCliTelemetry.js'\nexport * from './util/getEmptyAuth.js'\nexport * from './util/getSanityEnvVar.js'\nexport * from './util/getSanityUrl.js'\nexport * from './util/getUserConfig.js'\nexport * from './util/isCi.js'\nexport * from './util/isInteractive.js'\nexport * from './util/isRecord.js'\nexport * from './util/isStaging.js'\nexport * from './util/isTrueish.js'\nexport * from './util/normalizePath.js'\nexport * from './util/parseStringFlag.js'\nexport * from './util/readNDJSON.js'\nexport * from './util/readPackageJson.js'\nexport * from './util/resolveLocalPackage.js'\nexport * from './util/safeStructuredClone.js'\nexport * from './util/tryGetDefaultExport.js'\nexport * from './ux/colorizeJson.js'\nexport * from './ux/formatObject.js'\nexport * from './ux/printKeyValue.js'\nexport * from './ux/timer.js'\n"],"names":["doImport","clearCliTelemetry","CLI_TELEMETRY_SYMBOL","getCliTelemetry","setCliTelemetry"],"mappings":"AAAA,cAAc,+BAA8B;AAC5C,cAAc,mCAAkC;AAGhD,cAAc,8BAA6B;AAC3C,cAAc,kCAAiC;AAC/C,cAAc,qCAAoC;AAClD,cAAc,yCAAwC;AACtD,cAAc,oCAAmC;AACjD,cAAc,wCAAuC;AAErD,cAAc,aAAY;AAC1B,cAAc,uCAAsC;AACpD,cAAc,iCAAgC;AAC9C,cAAc,qBAAoB;AAClC,cAAc,0BAAyB;AACvC,cAAc,8BAA6B;AAC3C,cAAc,4BAA2B;AACzC,cAAc,sCAAqC;AACnD,cAAc,qCAAoC;AAClD,cAAc,sCAAqC;AACnD,cAAc,qCAAoC;AAOlD,cAAc,iCAAgC;AAC9C,SAAQA,QAAQ,QAAO,qBAAoB;AAC3C,cAAc,+CAA8C;AAC5D,cAAc,uBAAsB;AACpC,SACEC,iBAAiB,EACjBC,oBAAoB,EACpBC,eAAe,EACfC,eAAe,QACV,4BAA2B;AAClC,cAAc,yBAAwB;AACtC,cAAc,4BAA2B;AACzC,cAAc,yBAAwB;AACtC,cAAc,0BAAyB;AACvC,cAAc,iBAAgB;AAC9B,cAAc,0BAAyB;AACvC,cAAc,qBAAoB;AAClC,cAAc,sBAAqB;AACnC,cAAc,sBAAqB;AACnC,cAAc,0BAAyB;AACvC,cAAc,4BAA2B;AACzC,cAAc,uBAAsB;AACpC,cAAc,4BAA2B;AACzC,cAAc,gCAA+B;AAC7C,cAAc,gCAA+B;AAC7C,cAAc,gCAA+B;AAC7C,cAAc,uBAAsB;AACpC,cAAc,uBAAsB;AACpC,cAAc,wBAAuB;AACrC,cAAc,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './config/cli/getCliConfig.js'\nexport * from './config/cli/getCliConfigSync.js'\nexport {type CliConfig} from './config/cli/types/cliConfig.js'\nexport {type UserViteConfig} from './config/cli/types/userViteConfig.js'\nexport * from './config/findProjectRoot.js'\nexport * from './config/findProjectRootSync.js'\nexport * from './config/studio/getStudioConfig.js'\nexport * from './config/studio/getStudioWorkspaces.js'\nexport * from './config/util/findConfigsPaths.js'\nexport * from './config/util/findStudioConfigPath.js'\nexport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nexport * from './debug.js'\nexport * from './loaders/studio/studioWorkerTask.js'\nexport * from './loaders/tsx/tsxWorkerTask.js'\nexport * from './SanityCommand.js'\nexport * from './services/apiClient.js'\nexport * from './services/cliUserConfig.js'\nexport * from './services/getCliToken.js'\nexport * from './telemetry/createTelemetryStore.js'\nexport * from './telemetry/flushTelemetryFiles.js'\nexport * from './telemetry/getTelemetryBaseInfo.js'\nexport * from './telemetry/telemetryStoreDebug.js'\nexport {\n type CLITelemetryStore,\n type ConsentInformation,\n type TelemetryUserProperties,\n} from './telemetry/types.js'\nexport {type Output, type SanityOrgUser} from './types.js'\nexport * from './util/createExpiringConfig.js'\nexport {doImport} from './util/doImport.js'\nexport * from './util/environment/mockBrowserEnvironment.js'\nexport * from './util/fileExists.js'\nexport {\n clearCliTelemetry,\n CLI_TELEMETRY_SYMBOL,\n getCliTelemetry,\n setCliTelemetry,\n} from './util/getCliTelemetry.js'\nexport * from './util/getEmptyAuth.js'\nexport * from './util/getSanityEnvVar.js'\nexport * from './util/getSanityUrl.js'\nexport * from './util/getUserConfig.js'\nexport * from './util/importModule.js'\nexport * from './util/isCi.js'\nexport * from './util/isInteractive.js'\nexport * from './util/isRecord.js'\nexport * from './util/isStaging.js'\nexport * from './util/isTrueish.js'\nexport * from './util/normalizePath.js'\nexport * from './util/parseStringFlag.js'\nexport * from './util/promisifyWorker.js'\nexport * from './util/readNDJSON.js'\nexport * from './util/readPackageJson.js'\nexport * from './util/resolveLocalPackage.js'\nexport * from './util/safeStructuredClone.js'\nexport * from './util/tryGetDefaultExport.js'\nexport * from './ux/colorizeJson.js'\nexport * from './ux/formatObject.js'\nexport * from './ux/printKeyValue.js'\nexport * from './ux/timer.js'\n"],"names":["doImport","clearCliTelemetry","CLI_TELEMETRY_SYMBOL","getCliTelemetry","setCliTelemetry"],"mappings":"AAAA,cAAc,+BAA8B;AAC5C,cAAc,mCAAkC;AAGhD,cAAc,8BAA6B;AAC3C,cAAc,kCAAiC;AAC/C,cAAc,qCAAoC;AAClD,cAAc,yCAAwC;AACtD,cAAc,oCAAmC;AACjD,cAAc,wCAAuC;AAErD,cAAc,aAAY;AAC1B,cAAc,uCAAsC;AACpD,cAAc,iCAAgC;AAC9C,cAAc,qBAAoB;AAClC,cAAc,0BAAyB;AACvC,cAAc,8BAA6B;AAC3C,cAAc,4BAA2B;AACzC,cAAc,sCAAqC;AACnD,cAAc,qCAAoC;AAClD,cAAc,sCAAqC;AACnD,cAAc,qCAAoC;AAOlD,cAAc,iCAAgC;AAC9C,SAAQA,QAAQ,QAAO,qBAAoB;AAC3C,cAAc,+CAA8C;AAC5D,cAAc,uBAAsB;AACpC,SACEC,iBAAiB,EACjBC,oBAAoB,EACpBC,eAAe,EACfC,eAAe,QACV,4BAA2B;AAClC,cAAc,yBAAwB;AACtC,cAAc,4BAA2B;AACzC,cAAc,yBAAwB;AACtC,cAAc,0BAAyB;AACvC,cAAc,yBAAwB;AACtC,cAAc,iBAAgB;AAC9B,cAAc,0BAAyB;AACvC,cAAc,qBAAoB;AAClC,cAAc,sBAAqB;AACnC,cAAc,sBAAqB;AACnC,cAAc,0BAAyB;AACvC,cAAc,4BAA2B;AACzC,cAAc,4BAA2B;AACzC,cAAc,uBAAsB;AACpC,cAAc,4BAA2B;AACzC,cAAc,gCAA+B;AAC7C,cAAc,gCAA+B;AAC7C,cAAc,gCAA+B;AAC7C,cAAc,uBAAsB;AACpC,cAAc,uBAAsB;AACpC,cAAc,wBAAuB;AACrC,cAAc,gBAAe"}
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { isMainThread } from 'node:worker_threads';
|
|
2
|
-
import { createServer,
|
|
2
|
+
import { createServer, loadEnv, mergeConfig } from 'vite';
|
|
3
|
+
import { ViteNodeRunner } from 'vite-node/client';
|
|
4
|
+
import { ViteNodeServer } from 'vite-node/server';
|
|
5
|
+
import { installSourcemapsSupport } from 'vite-node/source-map';
|
|
3
6
|
import { getCliConfig } from '../../config/cli/getCliConfig.js';
|
|
7
|
+
import { subdebug } from '../../debug.js';
|
|
4
8
|
import { getStudioEnvironmentVariables } from '../../util/environment/getStudioEnvironmentVariables.js';
|
|
5
9
|
import { setupBrowserStubs } from '../../util/environment/setupBrowserStubs.js';
|
|
6
10
|
import { isRecord } from '../../util/isRecord.js';
|
|
@@ -12,12 +16,51 @@ const rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH;
|
|
|
12
16
|
if (!rootPath) {
|
|
13
17
|
throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable');
|
|
14
18
|
}
|
|
19
|
+
const debug = subdebug('studio:worker');
|
|
15
20
|
const workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE;
|
|
16
21
|
if (!workerScriptPath) {
|
|
17
22
|
throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable');
|
|
18
23
|
}
|
|
19
24
|
await setupBrowserStubs();
|
|
20
25
|
const studioEnvVars = await getStudioEnvironmentVariables(rootPath);
|
|
26
|
+
// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can
|
|
27
|
+
// extend/modify the default vite configuration for the studio.
|
|
28
|
+
let cliConfig;
|
|
29
|
+
try {
|
|
30
|
+
cliConfig = await getCliConfig(rootPath);
|
|
31
|
+
} catch (err) {
|
|
32
|
+
debug('Failed to load CLI config: %o', err);
|
|
33
|
+
if (!isNotFoundError(err)) {
|
|
34
|
+
// eslint-disable-next-line no-console
|
|
35
|
+
console.warn('[warn] Failed to load CLI config:', err);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Fetches and caches modules from HTTP/HTTPS URLs.
|
|
40
|
+
* Vite's SSR transform treats `https://` imports as external and bypasses the plugin
|
|
41
|
+
* resolve pipeline entirely, so we intercept them at the ViteNodeRunner level instead.
|
|
42
|
+
*/ const httpModuleCache = new Map();
|
|
43
|
+
async function fetchHttpModule(url) {
|
|
44
|
+
const cached = httpModuleCache.get(url);
|
|
45
|
+
if (cached) return {
|
|
46
|
+
code: cached
|
|
47
|
+
};
|
|
48
|
+
debug('Fetching HTTP import: %s', url);
|
|
49
|
+
const response = await fetch(url, {
|
|
50
|
+
signal: AbortSignal.timeout(30_000)
|
|
51
|
+
});
|
|
52
|
+
if (!response.ok) {
|
|
53
|
+
throw new Error(`Failed to fetch module from ${url}: ${response.status} ${response.statusText}`);
|
|
54
|
+
}
|
|
55
|
+
const code = await response.text();
|
|
56
|
+
httpModuleCache.set(url, code);
|
|
57
|
+
return {
|
|
58
|
+
code
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
function isHttpsUrl(id) {
|
|
62
|
+
return id.startsWith('https://');
|
|
63
|
+
}
|
|
21
64
|
const defaultViteConfig = {
|
|
22
65
|
build: {
|
|
23
66
|
target: 'node'
|
|
@@ -28,27 +71,28 @@ const defaultViteConfig = {
|
|
|
28
71
|
`process.env.${key}`,
|
|
29
72
|
JSON.stringify(value)
|
|
30
73
|
])),
|
|
74
|
+
// TODO: Combine with `determineIsApp` from `@sanity/cli`
|
|
75
|
+
envPrefix: cliConfig && 'app' in cliConfig ? 'SANITY_APP_' : 'SANITY_STUDIO_',
|
|
76
|
+
esbuild: {
|
|
77
|
+
jsx: 'automatic'
|
|
78
|
+
},
|
|
31
79
|
logLevel: 'error',
|
|
32
80
|
optimizeDeps: {
|
|
33
|
-
|
|
81
|
+
include: undefined,
|
|
82
|
+
noDiscovery: true
|
|
34
83
|
},
|
|
35
84
|
root: rootPath,
|
|
36
85
|
server: {
|
|
37
86
|
hmr: false,
|
|
38
87
|
watch: null
|
|
88
|
+
},
|
|
89
|
+
ssr: {
|
|
90
|
+
/**
|
|
91
|
+
* We don't want to externalize any dependencies, we want everything to run thru vite.
|
|
92
|
+
* Especially for CJS compatibility, etc.
|
|
93
|
+
*/ noExternal: true
|
|
39
94
|
}
|
|
40
95
|
};
|
|
41
|
-
// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can
|
|
42
|
-
// extend/modify the default vite configuration for the studio.
|
|
43
|
-
let cliConfig;
|
|
44
|
-
try {
|
|
45
|
-
cliConfig = await getCliConfig(rootPath);
|
|
46
|
-
} catch (err) {
|
|
47
|
-
if (!isNotFoundError(err)) {
|
|
48
|
-
// eslint-disable-next-line no-console
|
|
49
|
-
console.warn('[warn] Failed to load CLI config:', err);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
96
|
let viteConfig = defaultViteConfig;
|
|
53
97
|
if (typeof cliConfig?.vite === 'function') {
|
|
54
98
|
viteConfig = await cliConfig.vite(viteConfig, {
|
|
@@ -59,6 +103,7 @@ if (typeof cliConfig?.vite === 'function') {
|
|
|
59
103
|
} else if (isRecord(cliConfig?.vite)) {
|
|
60
104
|
viteConfig = mergeConfig(viteConfig, cliConfig.vite);
|
|
61
105
|
}
|
|
106
|
+
debug('Creating Vite server with config: %o', viteConfig);
|
|
62
107
|
// Vite will build the files we give it - targetting Node.js instead of the browser.
|
|
63
108
|
// We include the inject plugin in order to provide the stubs for the undefined global APIs.
|
|
64
109
|
const server = await createServer(viteConfig);
|
|
@@ -68,18 +113,52 @@ await server.pluginContainer.buildStart({});
|
|
|
68
113
|
// Note that Sanity also provides environment variables through `process.env.*` for compat reasons,
|
|
69
114
|
// and so we need to do the same here.
|
|
70
115
|
// @todo is this in line with sanity?
|
|
71
|
-
const env = loadEnv(server.config.mode, server.config.envDir, '');
|
|
116
|
+
const env = loadEnv(server.config.mode, server.config.envDir, viteConfig.envPrefix ?? '');
|
|
72
117
|
for(const key in env){
|
|
73
118
|
process.env[key] ??= env[key];
|
|
74
119
|
}
|
|
75
|
-
// Now we're
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
120
|
+
// Now we're providing the glue that ensures node-specific loading and execution works.
|
|
121
|
+
const node = new ViteNodeServer(server);
|
|
122
|
+
// Should make it easier to debug any crashes in the imported code…
|
|
123
|
+
installSourcemapsSupport({
|
|
124
|
+
getSourceMap: (source)=>node.getSourceMap(source)
|
|
125
|
+
});
|
|
126
|
+
const runner = new ViteNodeRunner({
|
|
127
|
+
base: server.config.base,
|
|
128
|
+
async fetchModule (id) {
|
|
129
|
+
// Vite's SSR transform externalizes https:// imports, so Node's ESM loader
|
|
130
|
+
// would reject them. We fetch the module over HTTP and run it through Vite's
|
|
131
|
+
// SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*
|
|
132
|
+
// format that ViteNodeRunner expects.
|
|
133
|
+
if (isHttpsUrl(id)) {
|
|
134
|
+
const { code: rawCode } = await fetchHttpModule(id);
|
|
135
|
+
const result = await server.ssrTransform(rawCode, null, id);
|
|
136
|
+
return {
|
|
137
|
+
code: result?.code || rawCode
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
return node.fetchModule(id);
|
|
141
|
+
},
|
|
142
|
+
resolveId (id, importer) {
|
|
143
|
+
// Prevent vite-node from trying to resolve HTTP URLs through Node's resolver
|
|
144
|
+
if (isHttpsUrl(id)) return {
|
|
145
|
+
id
|
|
146
|
+
};
|
|
147
|
+
// Resolve any import from an HTTP-fetched module against the remote origin
|
|
148
|
+
// (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)
|
|
149
|
+
if (importer && isHttpsUrl(importer)) {
|
|
150
|
+
return {
|
|
151
|
+
id: new URL(id, importer).href
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
return node.resolveId(id, importer);
|
|
155
|
+
},
|
|
156
|
+
root: server.config.root
|
|
79
157
|
});
|
|
80
|
-
//
|
|
81
|
-
|
|
82
|
-
//
|
|
83
|
-
await runner.
|
|
158
|
+
// Copied from `vite-node` - it appears that this applies the `define` config from
|
|
159
|
+
// vite, but it also takes a surprisingly long time to execute. Not clear at this
|
|
160
|
+
// point why this is, so we should investigate whether it's necessary or not.
|
|
161
|
+
await runner.executeId('/@vite/env');
|
|
162
|
+
await runner.executeId(workerScriptPath);
|
|
84
163
|
|
|
85
164
|
//# sourceMappingURL=studioWorkerLoader.worker.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {isMainThread} from 'node:worker_threads'\n\nimport {createServer, createServerModuleRunner, type InlineConfig, loadEnv, mergeConfig} from 'vite'\n\nimport {getCliConfig} from '../../config/cli/getCliConfig.js'\nimport {type CliConfig} from '../../config/cli/types/cliConfig.js'\nimport {getStudioEnvironmentVariables} from '../../util/environment/getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from '../../util/environment/setupBrowserStubs.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {isNotFoundError} from '../../util/NotFoundError.js'\n\nif (isMainThread) {\n throw new Error('Should be child of thread, not the main thread')\n}\n\nconst rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH\nif (!rootPath) {\n throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable')\n}\n\nconst workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE\nif (!workerScriptPath) {\n throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable')\n}\n\nawait setupBrowserStubs()\n\nconst studioEnvVars = await getStudioEnvironmentVariables(rootPath)\n\nconst defaultViteConfig: InlineConfig = {\n build: {target: 'node'},\n configFile: false, // @todo Should use `vite` prop from `sanity.cli.ts` (if any)\n // Inject environment variables as compile-time constants for Vite\n define: Object.fromEntries(\n Object.entries(studioEnvVars).map(([key, value]) => [\n `process.env.${key}`,\n JSON.stringify(value),\n ]),\n ),\n logLevel: 'error',\n optimizeDeps: {disabled: true}, // @todo is this necessary? cant remember why was added\n root: rootPath,\n server: {\n hmr: false,\n watch: null,\n },\n}\n\n// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can\n// extend/modify the default vite configuration for the studio.\nlet cliConfig: CliConfig | undefined\ntry {\n cliConfig = await getCliConfig(rootPath)\n} catch (err) {\n if (!isNotFoundError(err)) {\n // eslint-disable-next-line no-console\n console.warn('[warn] Failed to load CLI config:', err)\n }\n}\n\nlet viteConfig = defaultViteConfig\nif (typeof cliConfig?.vite === 'function') {\n viteConfig = (await cliConfig.vite(viteConfig, {\n command: 'build',\n isSsrBuild: true,\n mode: 'production',\n })) as InlineConfig\n} else if (isRecord(cliConfig?.vite)) {\n viteConfig = mergeConfig(viteConfig, cliConfig.vite)\n}\n\n// Vite will build the files we give it - targetting Node.js instead of the browser.\n// We include the inject plugin in order to provide the stubs for the undefined global APIs.\nconst server = await createServer(viteConfig)\n\n// Bit of a hack, but seems necessary based on the `node-vite` binary implementation\nawait server.pluginContainer.buildStart({})\n\n// Load environment variables from `.env` files in the same way as Vite does.\n// Note that Sanity also provides environment variables through `process.env.*` for compat reasons,\n// and so we need to do the same here.\n// @todo is this in line with sanity?\nconst env = loadEnv(server.config.mode, server.config.envDir, '')\nfor (const key in env) {\n process.env[key] ??= env[key]\n}\n\n// Now we're using Vite's Module Runner (replaces vite-node in Vite 4+)\nconst runner = await createServerModuleRunner(server.environments.ssr, {\n hmr: false,\n sourcemapInterceptor: 'prepareStackTrace',\n})\n\n// Apply the `define` config from vite - imports environment variables\nawait runner.import('/@vite/env')\n\n// Execute the worker script\nawait runner.import(workerScriptPath)\n"],"names":["isMainThread","createServer","createServerModuleRunner","loadEnv","mergeConfig","getCliConfig","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","isNotFoundError","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","defaultViteConfig","build","target","configFile","define","Object","fromEntries","entries","map","key","value","JSON","stringify","logLevel","optimizeDeps","disabled","root","server","hmr","watch","cliConfig","err","console","warn","viteConfig","vite","command","isSsrBuild","mode","pluginContainer","buildStart","config","envDir","runner","environments","ssr","sourcemapInterceptor","import"],"mappings":"AAAA,SAAQA,YAAY,QAAO,sBAAqB;AAEhD,SAAQC,YAAY,EAAEC,wBAAwB,EAAqBC,OAAO,EAAEC,WAAW,QAAO,OAAM;AAEpG,SAAQC,YAAY,QAAO,mCAAkC;AAE7D,SAAQC,6BAA6B,QAAO,0DAAyD;AACrG,SAAQC,iBAAiB,QAAO,8CAA6C;AAC7E,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,IAAIT,cAAc;IAChB,MAAM,IAAIU,MAAM;AAClB;AAEA,MAAMC,WAAWC,QAAQC,GAAG,CAACC,8BAA8B;AAC3D,IAAI,CAACH,UAAU;IACb,MAAM,IAAID,MAAM;AAClB;AAEA,MAAMK,mBAAmBH,QAAQC,GAAG,CAACG,uBAAuB;AAC5D,IAAI,CAACD,kBAAkB;IACrB,MAAM,IAAIL,MAAM;AAClB;AAEA,MAAMH;AAEN,MAAMU,gBAAgB,MAAMX,8BAA8BK;AAE1D,MAAMO,oBAAkC;IACtCC,OAAO;QAACC,QAAQ;IAAM;IACtBC,YAAY;IACZ,kEAAkE;IAClEC,QAAQC,OAAOC,WAAW,CACxBD,OAAOE,OAAO,CAACR,eAAeS,GAAG,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAK;YAClD,CAAC,YAAY,EAAED,KAAK;YACpBE,KAAKC,SAAS,CAACF;SAChB;IAEHG,UAAU;IACVC,cAAc;QAACC,UAAU;IAAI;IAC7BC,MAAMvB;IACNwB,QAAQ;QACNC,KAAK;QACLC,OAAO;IACT;AACF;AAEA,oFAAoF;AACpF,+DAA+D;AAC/D,IAAIC;AACJ,IAAI;IACFA,YAAY,MAAMjC,aAAaM;AACjC,EAAE,OAAO4B,KAAK;IACZ,IAAI,CAAC9B,gBAAgB8B,MAAM;QACzB,sCAAsC;QACtCC,QAAQC,IAAI,CAAC,qCAAqCF;IACpD;AACF;AAEA,IAAIG,aAAaxB;AACjB,IAAI,OAAOoB,WAAWK,SAAS,YAAY;IACzCD,aAAc,MAAMJ,UAAUK,IAAI,CAACD,YAAY;QAC7CE,SAAS;QACTC,YAAY;QACZC,MAAM;IACR;AACF,OAAO,IAAItC,SAAS8B,WAAWK,OAAO;IACpCD,aAAatC,YAAYsC,YAAYJ,UAAUK,IAAI;AACrD;AAEA,oFAAoF;AACpF,4FAA4F;AAC5F,MAAMR,SAAS,MAAMlC,aAAayC;AAElC,oFAAoF;AACpF,MAAMP,OAAOY,eAAe,CAACC,UAAU,CAAC,CAAC;AAEzC,6EAA6E;AAC7E,mGAAmG;AACnG,sCAAsC;AACtC,qCAAqC;AACrC,MAAMnC,MAAMV,QAAQgC,OAAOc,MAAM,CAACH,IAAI,EAAEX,OAAOc,MAAM,CAACC,MAAM,EAAE;AAC9D,IAAK,MAAMvB,OAAOd,IAAK;IACrBD,QAAQC,GAAG,CAACc,IAAI,KAAKd,GAAG,CAACc,IAAI;AAC/B;AAEA,uEAAuE;AACvE,MAAMwB,SAAS,MAAMjD,yBAAyBiC,OAAOiB,YAAY,CAACC,GAAG,EAAE;IACrEjB,KAAK;IACLkB,sBAAsB;AACxB;AAEA,sEAAsE;AACtE,MAAMH,OAAOI,MAAM,CAAC;AAEpB,4BAA4B;AAC5B,MAAMJ,OAAOI,MAAM,CAACxC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerLoader.worker.ts"],"sourcesContent":["import {isMainThread} from 'node:worker_threads'\n\nimport {createServer, type InlineConfig, loadEnv, mergeConfig} from 'vite'\nimport {ViteNodeRunner} from 'vite-node/client'\nimport {ViteNodeServer} from 'vite-node/server'\nimport {installSourcemapsSupport} from 'vite-node/source-map'\n\nimport {getCliConfig} from '../../config/cli/getCliConfig.js'\nimport {type CliConfig} from '../../config/cli/types/cliConfig.js'\nimport {subdebug} from '../../debug.js'\nimport {getStudioEnvironmentVariables} from '../../util/environment/getStudioEnvironmentVariables.js'\nimport {setupBrowserStubs} from '../../util/environment/setupBrowserStubs.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {isNotFoundError} from '../../util/NotFoundError.js'\n\nif (isMainThread) {\n throw new Error('Should be child of thread, not the main thread')\n}\n\nconst rootPath = process.env.STUDIO_WORKER_STUDIO_ROOT_PATH\nif (!rootPath) {\n throw new Error('Missing `STUDIO_WORKER_STUDIO_ROOT_PATH` environment variable')\n}\n\nconst debug = subdebug('studio:worker')\n\nconst workerScriptPath = process.env.STUDIO_WORKER_TASK_FILE\nif (!workerScriptPath) {\n throw new Error('Missing `STUDIO_WORKER_TASK_FILE` environment variable')\n}\n\nawait setupBrowserStubs()\n\nconst studioEnvVars = await getStudioEnvironmentVariables(rootPath)\n\n// Allow the CLI config (`sanity.cli.(js|ts)`) to define a `vite` property which can\n// extend/modify the default vite configuration for the studio.\nlet cliConfig: CliConfig | undefined\ntry {\n cliConfig = await getCliConfig(rootPath)\n} catch (err) {\n debug('Failed to load CLI config: %o', err)\n if (!isNotFoundError(err)) {\n // eslint-disable-next-line no-console\n console.warn('[warn] Failed to load CLI config:', err)\n }\n}\n\n/**\n * Fetches and caches modules from HTTP/HTTPS URLs.\n * Vite's SSR transform treats `https://` imports as external and bypasses the plugin\n * resolve pipeline entirely, so we intercept them at the ViteNodeRunner level instead.\n */\nconst httpModuleCache = new Map<string, string>()\nasync function fetchHttpModule(url: string): Promise<{code: string}> {\n const cached = httpModuleCache.get(url)\n if (cached) return {code: cached}\n\n debug('Fetching HTTP import: %s', url)\n const response = await fetch(url, {signal: AbortSignal.timeout(30_000)})\n if (!response.ok) {\n throw new Error(`Failed to fetch module from ${url}: ${response.status} ${response.statusText}`)\n }\n\n const code = await response.text()\n httpModuleCache.set(url, code)\n return {code}\n}\n\nfunction isHttpsUrl(id: string): boolean {\n return id.startsWith('https://')\n}\n\nconst defaultViteConfig: InlineConfig = {\n build: {target: 'node'},\n configFile: false, // @todo Should use `vite` prop from `sanity.cli.ts` (if any)\n // Inject environment variables as compile-time constants for Vite\n define: Object.fromEntries(\n Object.entries(studioEnvVars).map(([key, value]) => [\n `process.env.${key}`,\n JSON.stringify(value),\n ]),\n ),\n // TODO: Combine with `determineIsApp` from `@sanity/cli`\n envPrefix: cliConfig && 'app' in cliConfig ? 'SANITY_APP_' : 'SANITY_STUDIO_',\n esbuild: {\n jsx: 'automatic',\n },\n logLevel: 'error',\n optimizeDeps: {\n include: undefined,\n noDiscovery: true,\n },\n root: rootPath,\n server: {\n hmr: false,\n watch: null,\n },\n ssr: {\n /**\n * We don't want to externalize any dependencies, we want everything to run thru vite.\n * Especially for CJS compatibility, etc.\n */\n noExternal: true,\n },\n}\n\nlet viteConfig = defaultViteConfig\nif (typeof cliConfig?.vite === 'function') {\n viteConfig = (await cliConfig.vite(viteConfig, {\n command: 'build',\n isSsrBuild: true,\n mode: 'production',\n })) as InlineConfig\n} else if (isRecord(cliConfig?.vite)) {\n viteConfig = mergeConfig(viteConfig, cliConfig.vite)\n}\n\ndebug('Creating Vite server with config: %o', viteConfig)\n// Vite will build the files we give it - targetting Node.js instead of the browser.\n// We include the inject plugin in order to provide the stubs for the undefined global APIs.\nconst server = await createServer(viteConfig)\n\n// Bit of a hack, but seems necessary based on the `node-vite` binary implementation\nawait server.pluginContainer.buildStart({})\n\n// Load environment variables from `.env` files in the same way as Vite does.\n// Note that Sanity also provides environment variables through `process.env.*` for compat reasons,\n// and so we need to do the same here.\n// @todo is this in line with sanity?\nconst env = loadEnv(server.config.mode, server.config.envDir, viteConfig.envPrefix ?? '')\nfor (const key in env) {\n process.env[key] ??= env[key]\n}\n\n// Now we're providing the glue that ensures node-specific loading and execution works.\nconst node = new ViteNodeServer(server)\n\n// Should make it easier to debug any crashes in the imported code…\ninstallSourcemapsSupport({\n getSourceMap: (source) => node.getSourceMap(source),\n})\n\nconst runner = new ViteNodeRunner({\n base: server.config.base,\n async fetchModule(id) {\n // Vite's SSR transform externalizes https:// imports, so Node's ESM loader\n // would reject them. We fetch the module over HTTP and run it through Vite's\n // SSR transform to rewrite ESM export/import syntax to the __vite_ssr_*\n // format that ViteNodeRunner expects.\n if (isHttpsUrl(id)) {\n const {code: rawCode} = await fetchHttpModule(id)\n const result = await server.ssrTransform(rawCode, null, id)\n return {code: result?.code || rawCode}\n }\n return node.fetchModule(id)\n },\n resolveId(id, importer) {\n // Prevent vite-node from trying to resolve HTTP URLs through Node's resolver\n if (isHttpsUrl(id)) return {id}\n // Resolve any import from an HTTP-fetched module against the remote origin\n // (e.g. esm.sh returns `export * from '/pkg@1.0/es2022/pkg.mjs'`)\n if (importer && isHttpsUrl(importer)) {\n return {id: new URL(id, importer).href}\n }\n return node.resolveId(id, importer)\n },\n root: server.config.root,\n})\n\n// Copied from `vite-node` - it appears that this applies the `define` config from\n// vite, but it also takes a surprisingly long time to execute. Not clear at this\n// point why this is, so we should investigate whether it's necessary or not.\nawait runner.executeId('/@vite/env')\n\nawait runner.executeId(workerScriptPath)\n"],"names":["isMainThread","createServer","loadEnv","mergeConfig","ViteNodeRunner","ViteNodeServer","installSourcemapsSupport","getCliConfig","subdebug","getStudioEnvironmentVariables","setupBrowserStubs","isRecord","isNotFoundError","Error","rootPath","process","env","STUDIO_WORKER_STUDIO_ROOT_PATH","debug","workerScriptPath","STUDIO_WORKER_TASK_FILE","studioEnvVars","cliConfig","err","console","warn","httpModuleCache","Map","fetchHttpModule","url","cached","get","code","response","fetch","signal","AbortSignal","timeout","ok","status","statusText","text","set","isHttpsUrl","id","startsWith","defaultViteConfig","build","target","configFile","define","Object","fromEntries","entries","map","key","value","JSON","stringify","envPrefix","esbuild","jsx","logLevel","optimizeDeps","include","undefined","noDiscovery","root","server","hmr","watch","ssr","noExternal","viteConfig","vite","command","isSsrBuild","mode","pluginContainer","buildStart","config","envDir","node","getSourceMap","source","runner","base","fetchModule","rawCode","result","ssrTransform","resolveId","importer","URL","href","executeId"],"mappings":"AAAA,SAAQA,YAAY,QAAO,sBAAqB;AAEhD,SAAQC,YAAY,EAAqBC,OAAO,EAAEC,WAAW,QAAO,OAAM;AAC1E,SAAQC,cAAc,QAAO,mBAAkB;AAC/C,SAAQC,cAAc,QAAO,mBAAkB;AAC/C,SAAQC,wBAAwB,QAAO,uBAAsB;AAE7D,SAAQC,YAAY,QAAO,mCAAkC;AAE7D,SAAQC,QAAQ,QAAO,iBAAgB;AACvC,SAAQC,6BAA6B,QAAO,0DAAyD;AACrG,SAAQC,iBAAiB,QAAO,8CAA6C;AAC7E,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,IAAIZ,cAAc;IAChB,MAAM,IAAIa,MAAM;AAClB;AAEA,MAAMC,WAAWC,QAAQC,GAAG,CAACC,8BAA8B;AAC3D,IAAI,CAACH,UAAU;IACb,MAAM,IAAID,MAAM;AAClB;AAEA,MAAMK,QAAQV,SAAS;AAEvB,MAAMW,mBAAmBJ,QAAQC,GAAG,CAACI,uBAAuB;AAC5D,IAAI,CAACD,kBAAkB;IACrB,MAAM,IAAIN,MAAM;AAClB;AAEA,MAAMH;AAEN,MAAMW,gBAAgB,MAAMZ,8BAA8BK;AAE1D,oFAAoF;AACpF,+DAA+D;AAC/D,IAAIQ;AACJ,IAAI;IACFA,YAAY,MAAMf,aAAaO;AACjC,EAAE,OAAOS,KAAK;IACZL,MAAM,iCAAiCK;IACvC,IAAI,CAACX,gBAAgBW,MAAM;QACzB,sCAAsC;QACtCC,QAAQC,IAAI,CAAC,qCAAqCF;IACpD;AACF;AAEA;;;;CAIC,GACD,MAAMG,kBAAkB,IAAIC;AAC5B,eAAeC,gBAAgBC,GAAW;IACxC,MAAMC,SAASJ,gBAAgBK,GAAG,CAACF;IACnC,IAAIC,QAAQ,OAAO;QAACE,MAAMF;IAAM;IAEhCZ,MAAM,4BAA4BW;IAClC,MAAMI,WAAW,MAAMC,MAAML,KAAK;QAACM,QAAQC,YAAYC,OAAO,CAAC;IAAO;IACtE,IAAI,CAACJ,SAASK,EAAE,EAAE;QAChB,MAAM,IAAIzB,MAAM,CAAC,4BAA4B,EAAEgB,IAAI,EAAE,EAAEI,SAASM,MAAM,CAAC,CAAC,EAAEN,SAASO,UAAU,EAAE;IACjG;IAEA,MAAMR,OAAO,MAAMC,SAASQ,IAAI;IAChCf,gBAAgBgB,GAAG,CAACb,KAAKG;IACzB,OAAO;QAACA;IAAI;AACd;AAEA,SAASW,WAAWC,EAAU;IAC5B,OAAOA,GAAGC,UAAU,CAAC;AACvB;AAEA,MAAMC,oBAAkC;IACtCC,OAAO;QAACC,QAAQ;IAAM;IACtBC,YAAY;IACZ,kEAAkE;IAClEC,QAAQC,OAAOC,WAAW,CACxBD,OAAOE,OAAO,CAAChC,eAAeiC,GAAG,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAK;YAClD,CAAC,YAAY,EAAED,KAAK;YACpBE,KAAKC,SAAS,CAACF;SAChB;IAEH,yDAAyD;IACzDG,WAAWrC,aAAa,SAASA,YAAY,gBAAgB;IAC7DsC,SAAS;QACPC,KAAK;IACP;IACAC,UAAU;IACVC,cAAc;QACZC,SAASC;QACTC,aAAa;IACf;IACAC,MAAMrD;IACNsD,QAAQ;QACNC,KAAK;QACLC,OAAO;IACT;IACAC,KAAK;QACH;;;KAGC,GACDC,YAAY;IACd;AACF;AAEA,IAAIC,aAAa3B;AACjB,IAAI,OAAOxB,WAAWoD,SAAS,YAAY;IACzCD,aAAc,MAAMnD,UAAUoD,IAAI,CAACD,YAAY;QAC7CE,SAAS;QACTC,YAAY;QACZC,MAAM;IACR;AACF,OAAO,IAAIlE,SAASW,WAAWoD,OAAO;IACpCD,aAAatE,YAAYsE,YAAYnD,UAAUoD,IAAI;AACrD;AAEAxD,MAAM,wCAAwCuD;AAC9C,oFAAoF;AACpF,4FAA4F;AAC5F,MAAML,SAAS,MAAMnE,aAAawE;AAElC,oFAAoF;AACpF,MAAML,OAAOU,eAAe,CAACC,UAAU,CAAC,CAAC;AAEzC,6EAA6E;AAC7E,mGAAmG;AACnG,sCAAsC;AACtC,qCAAqC;AACrC,MAAM/D,MAAMd,QAAQkE,OAAOY,MAAM,CAACH,IAAI,EAAET,OAAOY,MAAM,CAACC,MAAM,EAAER,WAAWd,SAAS,IAAI;AACtF,IAAK,MAAMJ,OAAOvC,IAAK;IACrBD,QAAQC,GAAG,CAACuC,IAAI,KAAKvC,GAAG,CAACuC,IAAI;AAC/B;AAEA,uFAAuF;AACvF,MAAM2B,OAAO,IAAI7E,eAAe+D;AAEhC,mEAAmE;AACnE9D,yBAAyB;IACvB6E,cAAc,CAACC,SAAWF,KAAKC,YAAY,CAACC;AAC9C;AAEA,MAAMC,SAAS,IAAIjF,eAAe;IAChCkF,MAAMlB,OAAOY,MAAM,CAACM,IAAI;IACxB,MAAMC,aAAY3C,EAAE;QAClB,2EAA2E;QAC3E,6EAA6E;QAC7E,wEAAwE;QACxE,sCAAsC;QACtC,IAAID,WAAWC,KAAK;YAClB,MAAM,EAACZ,MAAMwD,OAAO,EAAC,GAAG,MAAM5D,gBAAgBgB;YAC9C,MAAM6C,SAAS,MAAMrB,OAAOsB,YAAY,CAACF,SAAS,MAAM5C;YACxD,OAAO;gBAACZ,MAAMyD,QAAQzD,QAAQwD;YAAO;QACvC;QACA,OAAON,KAAKK,WAAW,CAAC3C;IAC1B;IACA+C,WAAU/C,EAAE,EAAEgD,QAAQ;QACpB,6EAA6E;QAC7E,IAAIjD,WAAWC,KAAK,OAAO;YAACA;QAAE;QAC9B,2EAA2E;QAC3E,kEAAkE;QAClE,IAAIgD,YAAYjD,WAAWiD,WAAW;YACpC,OAAO;gBAAChD,IAAI,IAAIiD,IAAIjD,IAAIgD,UAAUE,IAAI;YAAA;QACxC;QACA,OAAOZ,KAAKS,SAAS,CAAC/C,IAAIgD;IAC5B;IACAzB,MAAMC,OAAOY,MAAM,CAACb,IAAI;AAC1B;AAEA,kFAAkF;AAClF,iFAAiF;AACjF,6EAA6E;AAC7E,MAAMkB,OAAOU,SAAS,CAAC;AAEvB,MAAMV,OAAOU,SAAS,CAAC5E"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
1
2
|
import { Worker } from 'node:worker_threads';
|
|
2
3
|
import { isRecord } from '../../util/isRecord.js';
|
|
4
|
+
import { promisifyWorker } from '../../util/promisifyWorker.js';
|
|
3
5
|
/**
|
|
4
6
|
* Executes a worker file in a Sanity Studio browser context.
|
|
5
7
|
*
|
|
@@ -28,32 +30,8 @@ import { isRecord } from '../../util/isRecord.js';
|
|
|
28
30
|
* @throws If the worker exits with a non-zero code
|
|
29
31
|
* @internal
|
|
30
32
|
*/ export function studioWorkerTask(filePath, options) {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
worker.addListener('error', function onWorkerError(err) {
|
|
34
|
-
reject(new Error(`Fail to load file through worker: ${err.message}`));
|
|
35
|
-
cleanup();
|
|
36
|
-
});
|
|
37
|
-
worker.addListener('exit', function onWorkerExit(code) {
|
|
38
|
-
if (code > 0) {
|
|
39
|
-
reject(new Error(`Worker exited with code ${code}`));
|
|
40
|
-
}
|
|
41
|
-
});
|
|
42
|
-
worker.addListener('messageerror', function onWorkerMessageError(err) {
|
|
43
|
-
reject(new Error(`Fail to parse message from worker: ${err}`));
|
|
44
|
-
cleanup();
|
|
45
|
-
});
|
|
46
|
-
worker.addListener('message', function onWorkerMessage(message) {
|
|
47
|
-
resolve(message);
|
|
48
|
-
cleanup();
|
|
49
|
-
});
|
|
50
|
-
function cleanup() {
|
|
51
|
-
// Allow the worker a _bit_ of time to clean up, but ensure that we don't have
|
|
52
|
-
// lingering processes hanging around forever if the worker doesn't exit on its
|
|
53
|
-
// own.
|
|
54
|
-
setImmediate(()=>worker.terminate());
|
|
55
|
-
}
|
|
56
|
-
});
|
|
33
|
+
const worker = createStudioWorker(filePath, options);
|
|
34
|
+
return promisifyWorker(worker);
|
|
57
35
|
}
|
|
58
36
|
/**
|
|
59
37
|
* Creates a new worker for a studio worker task.
|
|
@@ -83,7 +61,8 @@ import { isRecord } from '../../util/isRecord.js';
|
|
|
83
61
|
* @throws If the worker exits with a non-zero code
|
|
84
62
|
* @internal
|
|
85
63
|
*/ export function createStudioWorker(filePath, options) {
|
|
86
|
-
|
|
64
|
+
const normalizedFilePath = fileURLToPath(filePath);
|
|
65
|
+
if (!/\.worker\.(js|ts)$/.test(normalizedFilePath)) {
|
|
87
66
|
throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path');
|
|
88
67
|
}
|
|
89
68
|
return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {
|
|
@@ -91,7 +70,7 @@ import { isRecord } from '../../util/isRecord.js';
|
|
|
91
70
|
env: {
|
|
92
71
|
...isRecord(options.env) ? options.env : process.env,
|
|
93
72
|
STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,
|
|
94
|
-
STUDIO_WORKER_TASK_FILE:
|
|
73
|
+
STUDIO_WORKER_TASK_FILE: normalizedFilePath
|
|
95
74
|
}
|
|
96
75
|
});
|
|
97
76
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerTask.ts"],"sourcesContent":["import {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\n\n/**\n * Options for the studio worker task\n *\n * @internal\n */\ninterface StudioWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n studioRootPath: string\n}\n\n/**\n * Executes a worker file in a Sanity Studio browser context.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function studioWorkerTask<T = unknown>(\n filePath: URL,\n options: StudioWorkerTaskOptions,\n): Promise<T> {\n
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/studio/studioWorkerTask.ts"],"sourcesContent":["import {fileURLToPath} from 'node:url'\nimport {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\n\n/**\n * Options for the studio worker task\n *\n * @internal\n */\ninterface StudioWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n studioRootPath: string\n}\n\n/**\n * Executes a worker file in a Sanity Studio browser context.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function studioWorkerTask<T = unknown>(\n filePath: URL,\n options: StudioWorkerTaskOptions,\n): Promise<T> {\n const worker = createStudioWorker(filePath, options)\n return promisifyWorker<T>(worker)\n}\n\n/**\n * Creates a new worker for a studio worker task.\n *\n * This uses a combination of vite for \"bundling\" + jsdom for emulating a browser\n * environment under the hood, which means that the same thing that will work in vite\n * _should_ work in the worker - to a degree. If the user has defined any typescript\n * path aliases, these will have to be added as aliases to the vite config - the same\n * behavior as you would see with regular vite. Other things that are accounted for:\n *\n * - TypeScript support (+JSX, enums and other \"compilation needed\" features)\n * - CSS, font and other file imports will resolve to a file path\n * - CSS module imports will resolve to a javascript object of class names\n * - Environment variables are available both as `import.meta.env` and `process.env`,\n * and `.env` files are loaded in the same way that they would in a Sanity studio.\n * - Browser globals not available in a Node.js environment but _are_ provided by JSDOM\n * are defined directly to the Node environment as globals. While this polutes the\n * global namespace, it is done only in the worker thread.\n * - Certain browser globals that are _not_ available in JSDOM are also provided to the\n * global namespace - things like `requestIdleCallback`, `IntersectionObserver` etc.\n * These are provided with a minimal stub implementation to make them not crash.\n *\n * @param filePath - Path to the worker file (`.ts` works and is encouraged)\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function createStudioWorker(filePath: URL, options: StudioWorkerTaskOptions) {\n const normalizedFilePath = fileURLToPath(filePath)\n\n if (!/\\.worker\\.(js|ts)$/.test(normalizedFilePath)) {\n throw new Error('Studio worker tasks must include `.worker.(js|ts)` in path')\n }\n\n return new Worker(new URL('studioWorkerLoader.worker.js', import.meta.url), {\n ...options,\n env: {\n ...(isRecord(options.env) ? options.env : process.env),\n STUDIO_WORKER_STUDIO_ROOT_PATH: options.studioRootPath,\n STUDIO_WORKER_TASK_FILE: normalizedFilePath,\n },\n })\n}\n"],"names":["fileURLToPath","Worker","isRecord","promisifyWorker","studioWorkerTask","filePath","options","worker","createStudioWorker","normalizedFilePath","test","Error","URL","url","env","process","STUDIO_WORKER_STUDIO_ROOT_PATH","studioRootPath","STUDIO_WORKER_TASK_FILE"],"mappings":"AAAA,SAAQA,aAAa,QAAO,WAAU;AACtC,SAAQC,MAAM,QAA2B,sBAAqB;AAG9D,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,gCAA+B;AAW7D;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,iBACdC,QAAa,EACbC,OAAgC;IAEhC,MAAMC,SAASC,mBAAmBH,UAAUC;IAC5C,OAAOH,gBAAmBI;AAC5B;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,mBAAmBH,QAAa,EAAEC,OAAgC;IAChF,MAAMG,qBAAqBT,cAAcK;IAEzC,IAAI,CAAC,qBAAqBK,IAAI,CAACD,qBAAqB;QAClD,MAAM,IAAIE,MAAM;IAClB;IAEA,OAAO,IAAIV,OAAO,IAAIW,IAAI,gCAAgC,YAAYC,GAAG,GAAG;QAC1E,GAAGP,OAAO;QACVQ,KAAK;YACH,GAAIZ,SAASI,QAAQQ,GAAG,IAAIR,QAAQQ,GAAG,GAAGC,QAAQD,GAAG;YACrDE,gCAAgCV,QAAQW,cAAc;YACtDC,yBAAyBT;QAC3B;IACF;AACF"}
|
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { importModule } from '../../util/importModule.js';
|
|
2
2
|
const workerScript = process.env.TSX_WORKER_TASK_SCRIPT;
|
|
3
3
|
if (workerScript) {
|
|
4
|
-
await
|
|
5
|
-
|
|
6
|
-
tsconfig: process.env.TSX_TSCONFIG_PATH
|
|
4
|
+
await importModule(workerScript, {
|
|
5
|
+
tsconfigPath: process.env.TSX_TSCONFIG_PATH
|
|
7
6
|
});
|
|
8
7
|
} else {
|
|
9
8
|
throw new Error('`TX_WORKER_TASK_SCRIPT` not defined');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerLoader.worker.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerLoader.worker.ts"],"sourcesContent":["import {importModule} from '../../util/importModule.js'\n\nconst workerScript = process.env.TSX_WORKER_TASK_SCRIPT\n\nif (workerScript) {\n await importModule(workerScript, {\n tsconfigPath: process.env.TSX_TSCONFIG_PATH,\n })\n} else {\n throw new Error('`TX_WORKER_TASK_SCRIPT` not defined')\n}\n"],"names":["importModule","workerScript","process","env","TSX_WORKER_TASK_SCRIPT","tsconfigPath","TSX_TSCONFIG_PATH","Error"],"mappings":"AAAA,SAAQA,YAAY,QAAO,6BAA4B;AAEvD,MAAMC,eAAeC,QAAQC,GAAG,CAACC,sBAAsB;AAEvD,IAAIH,cAAc;IAChB,MAAMD,aAAaC,cAAc;QAC/BI,cAAcH,QAAQC,GAAG,CAACG,iBAAiB;IAC7C;AACF,OAAO;IACL,MAAM,IAAIC,MAAM;AAClB"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { URL } from 'node:url';
|
|
1
|
+
import { fileURLToPath, URL } from 'node:url';
|
|
2
2
|
import { Worker } from 'node:worker_threads';
|
|
3
3
|
import { getTsconfig } from 'get-tsconfig';
|
|
4
|
-
import { debug } from '../../debug.js';
|
|
5
4
|
import { isRecord } from '../../util/isRecord.js';
|
|
5
|
+
import { promisifyWorker } from '../../util/promisifyWorker.js';
|
|
6
6
|
/**
|
|
7
7
|
* Executes a worker file with tsx registered. This means you can import other
|
|
8
8
|
* typescript with fairly rich syntax, and still have that only apply to the worker
|
|
@@ -24,41 +24,13 @@ import { isRecord } from '../../util/isRecord.js';
|
|
|
24
24
|
...tsconfig?.path ? {
|
|
25
25
|
TSX_TSCONFIG_PATH: tsconfig.path
|
|
26
26
|
} : {},
|
|
27
|
-
TSX_WORKER_TASK_SCRIPT: filePath
|
|
27
|
+
TSX_WORKER_TASK_SCRIPT: fileURLToPath(filePath)
|
|
28
28
|
};
|
|
29
29
|
const worker = new Worker(new URL('tsxWorkerLoader.worker.js', import.meta.url), {
|
|
30
30
|
...options,
|
|
31
31
|
env
|
|
32
32
|
});
|
|
33
|
-
return
|
|
34
|
-
worker.addListener('error', function onWorkerError(err) {
|
|
35
|
-
debug(`Failed to load file through worker for: ${filePath.pathname}`, err);
|
|
36
|
-
reject(new Error(`Failed to load file through worker: ${err.message}`, {
|
|
37
|
-
cause: err
|
|
38
|
-
}));
|
|
39
|
-
cleanup();
|
|
40
|
-
});
|
|
41
|
-
worker.addListener('exit', function onWorkerExit(code) {
|
|
42
|
-
if (code > 0) {
|
|
43
|
-
reject(new Error(`Worker exited with code ${code}`));
|
|
44
|
-
}
|
|
45
|
-
});
|
|
46
|
-
worker.addListener('messageerror', function onWorkerMessageError(err) {
|
|
47
|
-
debug(`Failed to parse message from worker for: ${filePath.pathname}`, err);
|
|
48
|
-
reject(new Error(`Fail to parse message from worker: ${err}`));
|
|
49
|
-
cleanup();
|
|
50
|
-
});
|
|
51
|
-
worker.addListener('message', function onWorkerMessage(message) {
|
|
52
|
-
resolve(message);
|
|
53
|
-
cleanup();
|
|
54
|
-
});
|
|
55
|
-
function cleanup() {
|
|
56
|
-
// Allow the worker a _bit_ of time to clean up, but ensure that we don't have
|
|
57
|
-
// lingering processes hanging around forever if the worker doesn't exit on its
|
|
58
|
-
// own.
|
|
59
|
-
setImmediate(()=>worker.terminate());
|
|
60
|
-
}
|
|
61
|
-
});
|
|
33
|
+
return promisifyWorker(worker);
|
|
62
34
|
}
|
|
63
35
|
|
|
64
36
|
//# sourceMappingURL=tsxWorkerTask.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerTask.ts"],"sourcesContent":["import {URL} from 'node:url'\nimport {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {getTsconfig} from 'get-tsconfig'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/loaders/tsx/tsxWorkerTask.ts"],"sourcesContent":["import {fileURLToPath, URL} from 'node:url'\nimport {Worker, type WorkerOptions} from 'node:worker_threads'\n\nimport {getTsconfig} from 'get-tsconfig'\n\nimport {type RequireProps} from '../../types.js'\nimport {isRecord} from '../../util/isRecord.js'\nimport {promisifyWorker} from '../../util/promisifyWorker.js'\n\n/**\n * Options for the tsx worker task\n *\n * @internal\n */\ninterface TsxWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {\n rootPath: string\n}\n\n/**\n * Executes a worker file with tsx registered. This means you can import other\n * typescript with fairly rich syntax, and still have that only apply to the worker\n * thread instead of the full parent process. The worker should emit a message when\n * complete using `parentPort`. Once it has received a single message will resolve the\n * returned promise with that message. If you are expecting multiple messages, you will\n * have to implement another method ;)\n *\n * @param filePath - Path to the worker file\n * @param options - Options to pass to the worker\n * @returns A promise that resolves with the message from the worker\n * @throws If the file does not exist\n * @throws If the worker exits with a non-zero code\n * @internal\n */\nexport function tsxWorkerTask<T = unknown>(\n filePath: URL,\n options: TsxWorkerTaskOptions,\n): Promise<T> {\n const tsconfig = getTsconfig(options.rootPath)\n\n const env = {\n ...(isRecord(options.env) ? options.env : process.env),\n ...(tsconfig?.path ? {TSX_TSCONFIG_PATH: tsconfig.path} : {}),\n TSX_WORKER_TASK_SCRIPT: fileURLToPath(filePath),\n }\n\n const worker = new Worker(new URL('tsxWorkerLoader.worker.js', import.meta.url), {\n ...options,\n env,\n })\n\n return promisifyWorker<T>(worker)\n}\n"],"names":["fileURLToPath","URL","Worker","getTsconfig","isRecord","promisifyWorker","tsxWorkerTask","filePath","options","tsconfig","rootPath","env","process","path","TSX_TSCONFIG_PATH","TSX_WORKER_TASK_SCRIPT","worker","url"],"mappings":"AAAA,SAAQA,aAAa,EAAEC,GAAG,QAAO,WAAU;AAC3C,SAAQC,MAAM,QAA2B,sBAAqB;AAE9D,SAAQC,WAAW,QAAO,eAAc;AAGxC,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,gCAA+B;AAW7D;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASC,cACdC,QAAa,EACbC,OAA6B;IAE7B,MAAMC,WAAWN,YAAYK,QAAQE,QAAQ;IAE7C,MAAMC,MAAM;QACV,GAAIP,SAASI,QAAQG,GAAG,IAAIH,QAAQG,GAAG,GAAGC,QAAQD,GAAG;QACrD,GAAIF,UAAUI,OAAO;YAACC,mBAAmBL,SAASI,IAAI;QAAA,IAAI,CAAC,CAAC;QAC5DE,wBAAwBf,cAAcO;IACxC;IAEA,MAAMS,SAAS,IAAId,OAAO,IAAID,IAAI,6BAA6B,YAAYgB,GAAG,GAAG;QAC/E,GAAGT,OAAO;QACVG;IACF;IAEA,OAAON,gBAAmBW;AAC5B"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { getIt } from 'get-it';
|
|
2
|
+
import { debug, headers, httpErrors, promise } from 'get-it/middleware';
|
|
3
|
+
import { readPackageUpSync } from 'read-package-up';
|
|
4
|
+
let cachedPkg;
|
|
5
|
+
/**
|
|
6
|
+
* Creates a `get-it` requester with a standard set of middleware.
|
|
7
|
+
*
|
|
8
|
+
* Default middleware (in order):
|
|
9
|
+
* 1. `httpErrors()` — throw on HTTP error status codes
|
|
10
|
+
* 2. `headers({'User-Agent': '@sanity/cli-core@<version>'})` — identify CLI requests
|
|
11
|
+
* 3. `debug({verbose: true, namespace: 'sanity:cli'})` — debug logging
|
|
12
|
+
* 4. `promise({onlyBody: true})` — return body directly (must be last)
|
|
13
|
+
*
|
|
14
|
+
* @param options - Optional configuration to disable or customize middleware
|
|
15
|
+
* @returns A configured `get-it` requester
|
|
16
|
+
* @public
|
|
17
|
+
*/ export function createRequester(options) {
|
|
18
|
+
const opts = options?.middleware;
|
|
19
|
+
const middleware = [];
|
|
20
|
+
// 1. httpErrors
|
|
21
|
+
if (opts?.httpErrors !== false) {
|
|
22
|
+
middleware.push(httpErrors());
|
|
23
|
+
}
|
|
24
|
+
// 2. headers
|
|
25
|
+
if (opts?.headers !== false) {
|
|
26
|
+
const customHeaders = typeof opts?.headers === 'object' ? opts.headers : {};
|
|
27
|
+
const allHeaders = customHeaders['User-Agent'] ? {
|
|
28
|
+
...customHeaders
|
|
29
|
+
} : {
|
|
30
|
+
get ['User-Agent'] () {
|
|
31
|
+
const pkg = getPackageInfo();
|
|
32
|
+
return `${pkg.name}@${pkg.version}`;
|
|
33
|
+
},
|
|
34
|
+
...customHeaders
|
|
35
|
+
};
|
|
36
|
+
middleware.push(headers(allHeaders));
|
|
37
|
+
}
|
|
38
|
+
// 3. debug
|
|
39
|
+
if (opts?.debug !== false) {
|
|
40
|
+
const debugDefaults = {
|
|
41
|
+
namespace: 'sanity:cli',
|
|
42
|
+
verbose: true
|
|
43
|
+
};
|
|
44
|
+
const customDebug = typeof opts?.debug === 'object' ? opts.debug : {};
|
|
45
|
+
middleware.push(debug({
|
|
46
|
+
...debugDefaults,
|
|
47
|
+
...customDebug
|
|
48
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
// 4. promise (must be last)
|
|
51
|
+
if (opts?.promise !== false) {
|
|
52
|
+
const promiseDefaults = {
|
|
53
|
+
onlyBody: true
|
|
54
|
+
};
|
|
55
|
+
const customPromise = typeof opts?.promise === 'object' ? opts.promise : {};
|
|
56
|
+
middleware.push(promise({
|
|
57
|
+
...promiseDefaults,
|
|
58
|
+
...customPromise
|
|
59
|
+
}));
|
|
60
|
+
}
|
|
61
|
+
return getIt(middleware);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Reads the nearest `package.json` to determine the name and version of the `@sanity/cli-core` package.
|
|
65
|
+
*
|
|
66
|
+
* @returns The name and version of the package
|
|
67
|
+
* @internal
|
|
68
|
+
*/ function getPackageInfo() {
|
|
69
|
+
if (cachedPkg) return cachedPkg;
|
|
70
|
+
const result = readPackageUpSync({
|
|
71
|
+
cwd: import.meta.dirname
|
|
72
|
+
});
|
|
73
|
+
if (!result) {
|
|
74
|
+
throw new Error('Unable to resolve @sanity/cli-core package root');
|
|
75
|
+
}
|
|
76
|
+
cachedPkg = {
|
|
77
|
+
name: result.packageJson.name ?? '@sanity/cli-core',
|
|
78
|
+
version: result.packageJson.version ?? '0.0.0'
|
|
79
|
+
};
|
|
80
|
+
return cachedPkg;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
//# sourceMappingURL=createRequester.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/request/createRequester.ts"],"sourcesContent":["import {getIt, type Requester} from 'get-it'\nimport {debug, headers, httpErrors, promise} from 'get-it/middleware'\nimport {readPackageUpSync} from 'read-package-up'\n\nlet cachedPkg: {name: string; version: string} | undefined\n\n/**\n * Options for configuring individual middleware in {@link createRequester}.\n *\n * Each key corresponds to a middleware. Omitting a key uses the default,\n * `false` disables it, and an object merges with the defaults.\n *\n * @public\n */\nexport type MiddlewareOptions = {\n debug?: false | {namespace?: string; verbose?: boolean}\n headers?: false | Record<string, string>\n httpErrors?: false\n promise?: false | {onlyBody?: boolean}\n}\n\n/**\n * Creates a `get-it` requester with a standard set of middleware.\n *\n * Default middleware (in order):\n * 1. `httpErrors()` — throw on HTTP error status codes\n * 2. `headers({'User-Agent': '@sanity/cli-core@<version>'})` — identify CLI requests\n * 3. `debug({verbose: true, namespace: 'sanity:cli'})` — debug logging\n * 4. `promise({onlyBody: true})` — return body directly (must be last)\n *\n * @param options - Optional configuration to disable or customize middleware\n * @returns A configured `get-it` requester\n * @public\n */\nexport function createRequester(options?: {middleware?: MiddlewareOptions}): Requester {\n const opts = options?.middleware\n\n const middleware = []\n\n // 1. httpErrors\n if (opts?.httpErrors !== false) {\n middleware.push(httpErrors())\n }\n\n // 2. headers\n if (opts?.headers !== false) {\n const customHeaders = typeof opts?.headers === 'object' ? opts.headers : {}\n const allHeaders = customHeaders['User-Agent']\n ? {...customHeaders}\n : {\n get ['User-Agent']() {\n const pkg = getPackageInfo()\n return `${pkg.name}@${pkg.version}`\n },\n ...customHeaders,\n }\n middleware.push(headers(allHeaders))\n }\n\n // 3. debug\n if (opts?.debug !== false) {\n const debugDefaults = {namespace: 'sanity:cli', verbose: true}\n const customDebug = typeof opts?.debug === 'object' ? opts.debug : {}\n middleware.push(debug({...debugDefaults, ...customDebug}))\n }\n\n // 4. promise (must be last)\n if (opts?.promise !== false) {\n const promiseDefaults = {onlyBody: true}\n const customPromise = typeof opts?.promise === 'object' ? opts.promise : {}\n middleware.push(promise({...promiseDefaults, ...customPromise}))\n }\n\n return getIt(middleware)\n}\n\n/**\n * Reads the nearest `package.json` to determine the name and version of the `@sanity/cli-core` package.\n *\n * @returns The name and version of the package\n * @internal\n */\nfunction getPackageInfo(): {name: string; version: string} {\n if (cachedPkg) return cachedPkg\n\n const result = readPackageUpSync({cwd: import.meta.dirname})\n if (!result) {\n throw new Error('Unable to resolve @sanity/cli-core package root')\n }\n\n cachedPkg = {\n name: result.packageJson.name ?? '@sanity/cli-core',\n version: result.packageJson.version ?? '0.0.0',\n }\n return cachedPkg\n}\n"],"names":["getIt","debug","headers","httpErrors","promise","readPackageUpSync","cachedPkg","createRequester","options","opts","middleware","push","customHeaders","allHeaders","pkg","getPackageInfo","name","version","debugDefaults","namespace","verbose","customDebug","promiseDefaults","onlyBody","customPromise","result","cwd","dirname","Error","packageJson"],"mappings":"AAAA,SAAQA,KAAK,QAAuB,SAAQ;AAC5C,SAAQC,KAAK,EAAEC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAAO,oBAAmB;AACrE,SAAQC,iBAAiB,QAAO,kBAAiB;AAEjD,IAAIC;AAiBJ;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,gBAAgBC,OAA0C;IACxE,MAAMC,OAAOD,SAASE;IAEtB,MAAMA,aAAa,EAAE;IAErB,gBAAgB;IAChB,IAAID,MAAMN,eAAe,OAAO;QAC9BO,WAAWC,IAAI,CAACR;IAClB;IAEA,aAAa;IACb,IAAIM,MAAMP,YAAY,OAAO;QAC3B,MAAMU,gBAAgB,OAAOH,MAAMP,YAAY,WAAWO,KAAKP,OAAO,GAAG,CAAC;QAC1E,MAAMW,aAAaD,aAAa,CAAC,aAAa,GAC1C;YAAC,GAAGA,aAAa;QAAA,IACjB;YACE,IAAI,CAAC,aAAa,IAAG;gBACnB,MAAME,MAAMC;gBACZ,OAAO,GAAGD,IAAIE,IAAI,CAAC,CAAC,EAAEF,IAAIG,OAAO,EAAE;YACrC;YACA,GAAGL,aAAa;QAClB;QACJF,WAAWC,IAAI,CAACT,QAAQW;IAC1B;IAEA,WAAW;IACX,IAAIJ,MAAMR,UAAU,OAAO;QACzB,MAAMiB,gBAAgB;YAACC,WAAW;YAAcC,SAAS;QAAI;QAC7D,MAAMC,cAAc,OAAOZ,MAAMR,UAAU,WAAWQ,KAAKR,KAAK,GAAG,CAAC;QACpES,WAAWC,IAAI,CAACV,MAAM;YAAC,GAAGiB,aAAa;YAAE,GAAGG,WAAW;QAAA;IACzD;IAEA,4BAA4B;IAC5B,IAAIZ,MAAML,YAAY,OAAO;QAC3B,MAAMkB,kBAAkB;YAACC,UAAU;QAAI;QACvC,MAAMC,gBAAgB,OAAOf,MAAML,YAAY,WAAWK,KAAKL,OAAO,GAAG,CAAC;QAC1EM,WAAWC,IAAI,CAACP,QAAQ;YAAC,GAAGkB,eAAe;YAAE,GAAGE,aAAa;QAAA;IAC/D;IAEA,OAAOxB,MAAMU;AACf;AAEA;;;;;CAKC,GACD,SAASK;IACP,IAAIT,WAAW,OAAOA;IAEtB,MAAMmB,SAASpB,kBAAkB;QAACqB,KAAK,YAAYC,OAAO;IAAA;IAC1D,IAAI,CAACF,QAAQ;QACX,MAAM,IAAIG,MAAM;IAClB;IAEAtB,YAAY;QACVU,MAAMS,OAAOI,WAAW,CAACb,IAAI,IAAI;QACjCC,SAASQ,OAAOI,WAAW,CAACZ,OAAO,IAAI;IACzC;IACA,OAAOX;AACT"}
|
package/dist/util/doImport.js
CHANGED
|
@@ -9,8 +9,9 @@ import { pathToFileURL } from 'node:url';
|
|
|
9
9
|
// Absolute paths in windows are not valid URLs and are not supported by import().
|
|
10
10
|
// We need to convert the path to a file URL.
|
|
11
11
|
// See: https://github.com/nodejs/node/issues/31710
|
|
12
|
+
const url = /^file:\/\//.test(source) ? source : pathToFileURL(source).href;
|
|
12
13
|
// eslint-disable-next-line no-restricted-syntax
|
|
13
|
-
return import(
|
|
14
|
+
return import(/* @vite-ignore */ url);
|
|
14
15
|
}
|
|
15
16
|
|
|
16
17
|
//# sourceMappingURL=doImport.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/util/doImport.ts"],"sourcesContent":["// Only file that should be using dynamic import\nimport {pathToFileURL} from 'node:url'\n\n/**\n * This function is a replacement for built in dynamic import\n * This handles the case for windows file paths especially for absolute paths.\n *\n * @param source - File path\n */\nexport function doImport(source: string) {\n // Absolute paths in windows are not valid URLs and are not supported by import().\n // We need to convert the path to a file URL.\n // See: https://github.com/nodejs/node/issues/31710\n // eslint-disable-next-line no-restricted-syntax\n return import(
|
|
1
|
+
{"version":3,"sources":["../../src/util/doImport.ts"],"sourcesContent":["// Only file that should be using dynamic import\nimport {pathToFileURL} from 'node:url'\n\n/**\n * This function is a replacement for built in dynamic import\n * This handles the case for windows file paths especially for absolute paths.\n *\n * @param source - File path\n */\nexport function doImport(source: string) {\n // Absolute paths in windows are not valid URLs and are not supported by import().\n // We need to convert the path to a file URL.\n // See: https://github.com/nodejs/node/issues/31710\n const url = /^file:\\/\\//.test(source) ? source : pathToFileURL(source).href\n // eslint-disable-next-line no-restricted-syntax\n return import(\n /* @vite-ignore */\n url\n )\n}\n"],"names":["pathToFileURL","doImport","source","url","test","href"],"mappings":"AAAA,gDAAgD;AAChD,SAAQA,aAAa,QAAO,WAAU;AAEtC;;;;;CAKC,GACD,OAAO,SAASC,SAASC,MAAc;IACrC,kFAAkF;IAClF,6CAA6C;IAC7C,mDAAmD;IACnD,MAAMC,MAAM,aAAaC,IAAI,CAACF,UAAUA,SAASF,cAAcE,QAAQG,IAAI;IAC3E,gDAAgD;IAChD,OAAO,MAAM,CACX,gBAAgB,GAChBF;AAEJ"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
2
|
+
import { createJiti } from '@rexxars/jiti';
|
|
3
|
+
import { subdebug } from '../debug.js';
|
|
4
|
+
const debug = subdebug('importModule');
|
|
5
|
+
/**
|
|
6
|
+
* Imports a module using jiti and returns its exports.
|
|
7
|
+
* This is a thin wrapper around tsx to allow swapping out the underlying implementation in the future if needed.
|
|
8
|
+
*
|
|
9
|
+
* @param filePath - Path to the module to import.
|
|
10
|
+
* @param options - Options for the importModule function.
|
|
11
|
+
* @returns The exported module.
|
|
12
|
+
*
|
|
13
|
+
* @internal
|
|
14
|
+
*/ export async function importModule(filePath, options = {}) {
|
|
15
|
+
const { default: returnDefault = true, tsconfigPath } = options;
|
|
16
|
+
const jiti = createJiti(import.meta.url, {
|
|
17
|
+
debug: debug.enabled,
|
|
18
|
+
tsconfigPaths: typeof tsconfigPath === 'string' ? tsconfigPath : true
|
|
19
|
+
});
|
|
20
|
+
const fileURL = typeof filePath === 'string' ? pathToFileURL(filePath) : filePath;
|
|
21
|
+
debug(`Loading module: ${fileURLToPath(fileURL)}`, {
|
|
22
|
+
tsconfigPath
|
|
23
|
+
});
|
|
24
|
+
return jiti.import(fileURLToPath(fileURL), {
|
|
25
|
+
default: returnDefault
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
//# sourceMappingURL=importModule.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/util/importModule.ts"],"sourcesContent":["import {fileURLToPath, pathToFileURL} from 'node:url'\n\nimport {createJiti} from '@rexxars/jiti'\n\nimport {subdebug} from '../debug.js'\n\ninterface ImportModuleOptions {\n /**\n * Whether to return the default export of the module.\n */\n default?: true\n\n /**\n * Path to the tsconfig file to use for the import. If not provided, the tsconfig\n * will be inferred from the nearest `tsconfig.json` file.\n */\n tsconfigPath?: string\n}\n\nconst debug = subdebug('importModule')\n\n/**\n * Imports a module using jiti and returns its exports.\n * This is a thin wrapper around tsx to allow swapping out the underlying implementation in the future if needed.\n *\n * @param filePath - Path to the module to import.\n * @param options - Options for the importModule function.\n * @returns The exported module.\n *\n * @internal\n */\nexport async function importModule<T = unknown>(\n filePath: string | URL,\n options: ImportModuleOptions = {},\n): Promise<T> {\n const {default: returnDefault = true, tsconfigPath} = options\n\n const jiti = createJiti(import.meta.url, {\n debug: debug.enabled,\n tsconfigPaths: typeof tsconfigPath === 'string' ? tsconfigPath : true,\n })\n\n const fileURL = typeof filePath === 'string' ? pathToFileURL(filePath) : filePath\n\n debug(`Loading module: ${fileURLToPath(fileURL)}`, {tsconfigPath})\n\n return jiti.import<T>(fileURLToPath(fileURL), {default: returnDefault})\n}\n"],"names":["fileURLToPath","pathToFileURL","createJiti","subdebug","debug","importModule","filePath","options","default","returnDefault","tsconfigPath","jiti","url","enabled","tsconfigPaths","fileURL","import"],"mappings":"AAAA,SAAQA,aAAa,EAAEC,aAAa,QAAO,WAAU;AAErD,SAAQC,UAAU,QAAO,gBAAe;AAExC,SAAQC,QAAQ,QAAO,cAAa;AAepC,MAAMC,QAAQD,SAAS;AAEvB;;;;;;;;;CASC,GACD,OAAO,eAAeE,aACpBC,QAAsB,EACtBC,UAA+B,CAAC,CAAC;IAEjC,MAAM,EAACC,SAASC,gBAAgB,IAAI,EAAEC,YAAY,EAAC,GAAGH;IAEtD,MAAMI,OAAOT,WAAW,YAAYU,GAAG,EAAE;QACvCR,OAAOA,MAAMS,OAAO;QACpBC,eAAe,OAAOJ,iBAAiB,WAAWA,eAAe;IACnE;IAEA,MAAMK,UAAU,OAAOT,aAAa,WAAWL,cAAcK,YAAYA;IAEzEF,MAAM,CAAC,gBAAgB,EAAEJ,cAAce,UAAU,EAAE;QAACL;IAAY;IAEhE,OAAOC,KAAKK,MAAM,CAAIhB,cAAce,UAAU;QAACP,SAASC;IAAa;AACvE"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { subdebug } from '../debug.js';
|
|
2
|
+
const debug = subdebug('worker');
|
|
3
|
+
/**
|
|
4
|
+
* Wraps a Node.js Worker in a Promise that resolves with the first message
|
|
5
|
+
* the worker sends, and rejects on error, message deserialization failure,
|
|
6
|
+
* or non-zero exit code. The worker is terminated after a message or error
|
|
7
|
+
* is received.
|
|
8
|
+
*
|
|
9
|
+
* @param worker - The Worker instance to promisify
|
|
10
|
+
* @returns A promise that resolves with the first message from the worker
|
|
11
|
+
* @throws If the worker emits an error, a message deserialization error, or exits with a non-zero code
|
|
12
|
+
* @internal
|
|
13
|
+
*/ export function promisifyWorker(worker) {
|
|
14
|
+
return new Promise((resolve, reject)=>{
|
|
15
|
+
let settled = false;
|
|
16
|
+
worker.addListener('error', function onWorkerError(err) {
|
|
17
|
+
settled = true;
|
|
18
|
+
debug(`Worker error: ${err.message}`, err);
|
|
19
|
+
reject(new Error(`Worker error: ${err.message}`, {
|
|
20
|
+
cause: err
|
|
21
|
+
}));
|
|
22
|
+
cleanup();
|
|
23
|
+
});
|
|
24
|
+
// No cleanup() here — the worker is already dead after exiting,
|
|
25
|
+
// so there is nothing to terminate or remove listeners from.
|
|
26
|
+
worker.addListener('exit', function onWorkerExit(code) {
|
|
27
|
+
if (code > 0) {
|
|
28
|
+
debug(`Worker exited with code ${code}`);
|
|
29
|
+
reject(new Error(`Worker exited with code ${code}`));
|
|
30
|
+
} else if (!settled) {
|
|
31
|
+
debug('Worker exited with code 0 without sending a message');
|
|
32
|
+
reject(new Error('Worker exited without sending a message'));
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
worker.addListener('messageerror', function onWorkerMessageError(err) {
|
|
36
|
+
settled = true;
|
|
37
|
+
debug(`Worker message error: ${err.message}`, err);
|
|
38
|
+
reject(new Error(`Failed to deserialize worker message: ${err}`));
|
|
39
|
+
cleanup();
|
|
40
|
+
});
|
|
41
|
+
worker.addListener('message', function onWorkerMessage(message) {
|
|
42
|
+
settled = true;
|
|
43
|
+
debug('Worker message %o', message);
|
|
44
|
+
resolve(message);
|
|
45
|
+
cleanup();
|
|
46
|
+
});
|
|
47
|
+
function cleanup() {
|
|
48
|
+
setImmediate(()=>worker.terminate());
|
|
49
|
+
worker.removeAllListeners();
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
//# sourceMappingURL=promisifyWorker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/util/promisifyWorker.ts"],"sourcesContent":["import {type Worker} from 'node:worker_threads'\n\nimport {subdebug} from '../debug.js'\n\nconst debug = subdebug('worker')\n\n/**\n * Wraps a Node.js Worker in a Promise that resolves with the first message\n * the worker sends, and rejects on error, message deserialization failure,\n * or non-zero exit code. The worker is terminated after a message or error\n * is received.\n *\n * @param worker - The Worker instance to promisify\n * @returns A promise that resolves with the first message from the worker\n * @throws If the worker emits an error, a message deserialization error, or exits with a non-zero code\n * @internal\n */\nexport function promisifyWorker<T = unknown>(worker: Worker): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let settled = false\n\n worker.addListener('error', function onWorkerError(err) {\n settled = true\n debug(`Worker error: ${err.message}`, err)\n reject(new Error(`Worker error: ${err.message}`, {cause: err}))\n cleanup()\n })\n // No cleanup() here — the worker is already dead after exiting,\n // so there is nothing to terminate or remove listeners from.\n worker.addListener('exit', function onWorkerExit(code) {\n if (code > 0) {\n debug(`Worker exited with code ${code}`)\n reject(new Error(`Worker exited with code ${code}`))\n } else if (!settled) {\n debug('Worker exited with code 0 without sending a message')\n reject(new Error('Worker exited without sending a message'))\n }\n })\n worker.addListener('messageerror', function onWorkerMessageError(err) {\n settled = true\n debug(`Worker message error: ${err.message}`, err)\n reject(new Error(`Failed to deserialize worker message: ${err}`))\n cleanup()\n })\n worker.addListener('message', function onWorkerMessage(message) {\n settled = true\n debug('Worker message %o', message)\n resolve(message)\n cleanup()\n })\n\n function cleanup() {\n setImmediate(() => worker.terminate())\n worker.removeAllListeners()\n }\n })\n}\n"],"names":["subdebug","debug","promisifyWorker","worker","Promise","resolve","reject","settled","addListener","onWorkerError","err","message","Error","cause","cleanup","onWorkerExit","code","onWorkerMessageError","onWorkerMessage","setImmediate","terminate","removeAllListeners"],"mappings":"AAEA,SAAQA,QAAQ,QAAO,cAAa;AAEpC,MAAMC,QAAQD,SAAS;AAEvB;;;;;;;;;;CAUC,GACD,OAAO,SAASE,gBAA6BC,MAAc;IACzD,OAAO,IAAIC,QAAW,CAACC,SAASC;QAC9B,IAAIC,UAAU;QAEdJ,OAAOK,WAAW,CAAC,SAAS,SAASC,cAAcC,GAAG;YACpDH,UAAU;YACVN,MAAM,CAAC,cAAc,EAAES,IAAIC,OAAO,EAAE,EAAED;YACtCJ,OAAO,IAAIM,MAAM,CAAC,cAAc,EAAEF,IAAIC,OAAO,EAAE,EAAE;gBAACE,OAAOH;YAAG;YAC5DI;QACF;QACA,gEAAgE;QAChE,6DAA6D;QAC7DX,OAAOK,WAAW,CAAC,QAAQ,SAASO,aAAaC,IAAI;YACnD,IAAIA,OAAO,GAAG;gBACZf,MAAM,CAAC,wBAAwB,EAAEe,MAAM;gBACvCV,OAAO,IAAIM,MAAM,CAAC,wBAAwB,EAAEI,MAAM;YACpD,OAAO,IAAI,CAACT,SAAS;gBACnBN,MAAM;gBACNK,OAAO,IAAIM,MAAM;YACnB;QACF;QACAT,OAAOK,WAAW,CAAC,gBAAgB,SAASS,qBAAqBP,GAAG;YAClEH,UAAU;YACVN,MAAM,CAAC,sBAAsB,EAAES,IAAIC,OAAO,EAAE,EAAED;YAC9CJ,OAAO,IAAIM,MAAM,CAAC,sCAAsC,EAAEF,KAAK;YAC/DI;QACF;QACAX,OAAOK,WAAW,CAAC,WAAW,SAASU,gBAAgBP,OAAO;YAC5DJ,UAAU;YACVN,MAAM,qBAAqBU;YAC3BN,QAAQM;YACRG;QACF;QAEA,SAASA;YACPK,aAAa,IAAMhB,OAAOiB,SAAS;YACnCjB,OAAOkB,kBAAkB;QAC3B;IACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/cli-core",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.16",
|
|
4
4
|
"description": "Sanity CLI core package",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -35,6 +35,10 @@
|
|
|
35
35
|
"source": "./src/_exports/ux.ts",
|
|
36
36
|
"default": "./dist/_exports/ux.js"
|
|
37
37
|
},
|
|
38
|
+
"./request": {
|
|
39
|
+
"source": "./src/_exports/request.ts",
|
|
40
|
+
"default": "./dist/_exports/request.js"
|
|
41
|
+
},
|
|
38
42
|
"./package.json": "./package.json"
|
|
39
43
|
},
|
|
40
44
|
"main": "./dist/index.js",
|
|
@@ -45,28 +49,32 @@
|
|
|
45
49
|
"dependencies": {
|
|
46
50
|
"@inquirer/prompts": "^8.2.0",
|
|
47
51
|
"@oclif/core": "^4.8.0",
|
|
48
|
-
"@
|
|
49
|
-
"@sanity/
|
|
52
|
+
"@rexxars/jiti": "^2.6.2",
|
|
53
|
+
"@sanity/client": "^7.16.0",
|
|
54
|
+
"@sanity/types": "^5.12.0",
|
|
50
55
|
"babel-plugin-react-compiler": "^1.0.0",
|
|
51
56
|
"boxen": "^8.0.1",
|
|
52
57
|
"configstore": "^7.0.0",
|
|
53
58
|
"debug": "^4.4.3",
|
|
59
|
+
"get-it": "^8.7.0",
|
|
54
60
|
"get-tsconfig": "^4.13.6",
|
|
55
61
|
"import-meta-resolve": "^4.2.0",
|
|
56
62
|
"jsdom": "^27.4.0",
|
|
57
63
|
"json-lexer": "^1.2.0",
|
|
58
64
|
"log-symbols": "^7.0.1",
|
|
59
65
|
"ora": "^9.0.0",
|
|
66
|
+
"read-package-up": "^12.0.0",
|
|
60
67
|
"rxjs": "^7.8.2",
|
|
61
68
|
"tinyglobby": "^0.2.15",
|
|
62
69
|
"tsx": "^4.21.0",
|
|
63
70
|
"typeid-js": "^1.2.0",
|
|
64
71
|
"vite": "^7.3.1",
|
|
72
|
+
"vite-node": "^5.3.0",
|
|
65
73
|
"zod": "^4.3.6"
|
|
66
74
|
},
|
|
67
75
|
"devDependencies": {
|
|
68
76
|
"@eslint/compat": "^2.0.2",
|
|
69
|
-
"@sanity/codegen": "^5.
|
|
77
|
+
"@sanity/codegen": "^5.10.1",
|
|
70
78
|
"@sanity/pkg-utils": "^10.4.4",
|
|
71
79
|
"@sanity/telemetry": "^0.8.1",
|
|
72
80
|
"@swc/cli": "^0.8.0",
|
|
@@ -76,12 +84,12 @@
|
|
|
76
84
|
"@types/node": "^20.19.33",
|
|
77
85
|
"eslint": "^9.39.2",
|
|
78
86
|
"publint": "^0.3.17",
|
|
79
|
-
"sanity": "^5.
|
|
87
|
+
"sanity": "^5.12.0",
|
|
80
88
|
"typescript": "^5.9.3",
|
|
81
89
|
"vitest": "^4.0.18",
|
|
82
90
|
"@repo/package.config": "0.0.1",
|
|
83
|
-
"@
|
|
84
|
-
"@
|
|
91
|
+
"@repo/tsconfig": "3.70.0",
|
|
92
|
+
"@sanity/eslint-config-cli": "0.0.0-alpha.2"
|
|
85
93
|
},
|
|
86
94
|
"peerDependencies": {
|
|
87
95
|
"@sanity/telemetry": ">=0.8.1 <0.9.0"
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
2
|
-
import { z } from 'zod';
|
|
3
|
-
import { doImport } from '../../util/doImport.js';
|
|
4
|
-
if (isMainThread || !parentPort) {
|
|
5
|
-
throw new Error('Should only be run in a worker!');
|
|
6
|
-
}
|
|
7
|
-
const { configPath } = z.object({
|
|
8
|
-
configPath: z.string()
|
|
9
|
-
}).parse(workerData);
|
|
10
|
-
const { default: loadedConfig } = await doImport(configPath);
|
|
11
|
-
// This might throw on unserializable properties, but that's actually wanted in this
|
|
12
|
-
// case, since we _need_ any unserializable props (such as vite config functions)
|
|
13
|
-
parentPort.postMessage(loadedConfig);
|
|
14
|
-
|
|
15
|
-
//# sourceMappingURL=getCliConfig.worker.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/config/cli/getCliConfig.worker.ts"],"sourcesContent":["import {isMainThread, parentPort, workerData} from 'node:worker_threads'\n\nimport {z} from 'zod'\n\nimport {doImport} from '../../util/doImport.js'\n\nif (isMainThread || !parentPort) {\n throw new Error('Should only be run in a worker!')\n}\n\nconst {configPath} = z.object({configPath: z.string()}).parse(workerData)\n\nconst {default: loadedConfig} = await doImport(configPath)\n\n// This might throw on unserializable properties, but that's actually wanted in this\n// case, since we _need_ any unserializable props (such as vite config functions)\nparentPort.postMessage(loadedConfig)\n"],"names":["isMainThread","parentPort","workerData","z","doImport","Error","configPath","object","string","parse","default","loadedConfig","postMessage"],"mappings":"AAAA,SAAQA,YAAY,EAAEC,UAAU,EAAEC,UAAU,QAAO,sBAAqB;AAExE,SAAQC,CAAC,QAAO,MAAK;AAErB,SAAQC,QAAQ,QAAO,yBAAwB;AAE/C,IAAIJ,gBAAgB,CAACC,YAAY;IAC/B,MAAM,IAAII,MAAM;AAClB;AAEA,MAAM,EAACC,UAAU,EAAC,GAAGH,EAAEI,MAAM,CAAC;IAACD,YAAYH,EAAEK,MAAM;AAAE,GAAGC,KAAK,CAACP;AAE9D,MAAM,EAACQ,SAASC,YAAY,EAAC,GAAG,MAAMP,SAASE;AAE/C,oFAAoF;AACpF,iFAAiF;AACjFL,WAAWW,WAAW,CAACD"}
|