@sanity/runtime-cli 4.3.3 → 4.3.5-bundle.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +17 -17
  2. package/dist/actions/blueprints/assets.d.ts +1 -0
  3. package/dist/actions/blueprints/assets.js +21 -4
  4. package/dist/actions/functions/test.d.ts +2 -2
  5. package/dist/actions/functions/test.js +2 -2
  6. package/dist/commands/blueprints/config.d.ts +1 -1
  7. package/dist/commands/blueprints/config.js +8 -8
  8. package/dist/commands/blueprints/deploy.js +3 -4
  9. package/dist/commands/blueprints/init.d.ts +1 -1
  10. package/dist/commands/blueprints/init.js +8 -8
  11. package/dist/commands/functions/logs.d.ts +1 -1
  12. package/dist/commands/functions/logs.js +8 -8
  13. package/dist/commands/functions/test.js +3 -6
  14. package/dist/server/app.js +80 -12
  15. package/dist/server/static/api.js +24 -3
  16. package/dist/server/static/components/app.css +915 -54
  17. package/dist/server/static/components/dataset-dropdown.js +5 -3
  18. package/dist/server/static/components/filters.d.ts +1 -0
  19. package/dist/server/static/components/filters.js +20 -0
  20. package/dist/server/static/components/function-list.js +7 -7
  21. package/dist/server/static/components/payload-panel.js +18 -17
  22. package/dist/server/static/components/projects-dropdown.js +5 -3
  23. package/dist/server/static/components/response-panel.js +38 -28
  24. package/dist/server/static/index.html +11 -30
  25. package/dist/server/static/vendor/vendor.bundle.d.ts +2 -2
  26. package/dist/utils/build-payload.d.ts +1 -1
  27. package/dist/utils/build-payload.js +3 -3
  28. package/dist/utils/bundle/bundle-function.d.ts +8 -0
  29. package/dist/utils/bundle/bundle-function.js +125 -0
  30. package/dist/utils/bundle/cleanup-source-maps.d.ts +10 -0
  31. package/dist/utils/bundle/cleanup-source-maps.js +53 -0
  32. package/dist/utils/bundle/find-up.d.ts +16 -0
  33. package/dist/utils/bundle/find-up.js +39 -0
  34. package/dist/utils/bundle/verify-handler.d.ts +2 -0
  35. package/dist/utils/bundle/verify-handler.js +13 -0
  36. package/dist/utils/child-process-wrapper.js +8 -6
  37. package/dist/utils/functions/find-entry-point.d.ts +11 -0
  38. package/dist/utils/functions/find-entry-point.js +75 -0
  39. package/dist/utils/functions/should-bundle.d.ts +2 -0
  40. package/dist/utils/functions/should-bundle.js +23 -0
  41. package/dist/utils/invoke-local.d.ts +2 -2
  42. package/dist/utils/invoke-local.js +48 -7
  43. package/dist/utils/is-record.d.ts +1 -0
  44. package/dist/utils/is-record.js +3 -0
  45. package/dist/utils/parse-json-object.d.ts +1 -0
  46. package/dist/utils/parse-json-object.js +10 -0
  47. package/dist/utils/types.d.ts +3 -1
  48. package/oclif.manifest.json +1 -1
  49. package/package.json +4 -1
  50. package/dist/utils/is-json.d.ts +0 -1
  51. package/dist/utils/is-json.js +0 -12
package/README.md CHANGED
@@ -20,7 +20,7 @@ $ npm install -g @sanity/runtime-cli
20
20
  $ sanity-run COMMAND
21
21
  running command...
22
22
  $ sanity-run (--version)
23
- @sanity/runtime-cli/4.3.3 linux-x64 node-v22.14.0
23
+ @sanity/runtime-cli/4.3.5-bundle.0 darwin-arm64 node-v22.14.0
24
24
  $ sanity-run --help [COMMAND]
25
25
  USAGE
26
26
  $ sanity-run COMMAND
@@ -74,7 +74,7 @@ EXAMPLES
74
74
  $ sanity-run blueprints add function --name my-function --function-type document-publish
75
75
  ```
76
76
 
77
- _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/blueprints/add.ts)_
77
+ _See code: [src/commands/blueprints/add.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/blueprints/add.ts)_
78
78
 
79
79
  ## `sanity-run blueprints config`
80
80
 
@@ -103,7 +103,7 @@ EXAMPLES
103
103
  $ sanity-run blueprints config --edit --project-id <projectId> --stack-id <stackId>
104
104
  ```
105
105
 
106
- _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/blueprints/config.ts)_
106
+ _See code: [src/commands/blueprints/config.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/blueprints/config.ts)_
107
107
 
108
108
  ## `sanity-run blueprints deploy`
109
109
 
@@ -123,7 +123,7 @@ EXAMPLES
123
123
  $ sanity-run blueprints deploy
124
124
  ```
125
125
 
126
- _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/blueprints/deploy.ts)_
126
+ _See code: [src/commands/blueprints/deploy.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/blueprints/deploy.ts)_
127
127
 
128
128
  ## `sanity-run blueprints destroy`
129
129
 
@@ -146,7 +146,7 @@ EXAMPLES
146
146
  $ sanity-run blueprints destroy --id ST-a1b2c3
147
147
  ```
148
148
 
149
- _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/blueprints/destroy.ts)_
149
+ _See code: [src/commands/blueprints/destroy.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/blueprints/destroy.ts)_
150
150
 
151
151
  ## `sanity-run blueprints info`
152
152
 
@@ -168,7 +168,7 @@ EXAMPLES
168
168
  $ sanity-run blueprints info --id ST-a1b2c3
169
169
  ```
170
170
 
171
- _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/blueprints/info.ts)_
171
+ _See code: [src/commands/blueprints/info.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/blueprints/info.ts)_
172
172
 
173
173
  ## `sanity-run blueprints init`
174
174
 
@@ -198,7 +198,7 @@ EXAMPLES
198
198
  $ sanity-run blueprints init --blueprint-type <json|js|ts> --project-id <projectId> --stack-name <stackName>
199
199
  ```
200
200
 
201
- _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/blueprints/init.ts)_
201
+ _See code: [src/commands/blueprints/init.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/blueprints/init.ts)_
202
202
 
203
203
  ## `sanity-run blueprints logs`
204
204
 
@@ -220,7 +220,7 @@ EXAMPLES
220
220
  $ sanity-run blueprints logs --watch
221
221
  ```
222
222
 
223
- _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/blueprints/logs.ts)_
223
+ _See code: [src/commands/blueprints/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/blueprints/logs.ts)_
224
224
 
225
225
  ## `sanity-run blueprints plan`
226
226
 
@@ -237,7 +237,7 @@ EXAMPLES
237
237
  $ sanity-run blueprints plan
238
238
  ```
239
239
 
240
- _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/blueprints/plan.ts)_
240
+ _See code: [src/commands/blueprints/plan.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/blueprints/plan.ts)_
241
241
 
242
242
  ## `sanity-run blueprints stacks`
243
243
 
@@ -259,7 +259,7 @@ EXAMPLES
259
259
  $ sanity-run blueprints stacks --projectId a1b2c3
260
260
  ```
261
261
 
262
- _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/blueprints/stacks.ts)_
262
+ _See code: [src/commands/blueprints/stacks.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/blueprints/stacks.ts)_
263
263
 
264
264
  ## `sanity-run functions dev`
265
265
 
@@ -279,7 +279,7 @@ EXAMPLES
279
279
  $ sanity-run functions dev --port 8974
280
280
  ```
281
281
 
282
- _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/functions/dev.ts)_
282
+ _See code: [src/commands/functions/dev.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/functions/dev.ts)_
283
283
 
284
284
  ## `sanity-run functions env add NAME KEY VALUE`
285
285
 
@@ -301,7 +301,7 @@ EXAMPLES
301
301
  $ sanity-run functions env add MyFunction API_URL https://api.example.com/
302
302
  ```
303
303
 
304
- _See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/functions/env/add.ts)_
304
+ _See code: [src/commands/functions/env/add.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/functions/env/add.ts)_
305
305
 
306
306
  ## `sanity-run functions env list NAME`
307
307
 
@@ -321,7 +321,7 @@ EXAMPLES
321
321
  $ sanity-run functions env list MyFunction
322
322
  ```
323
323
 
324
- _See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/functions/env/list.ts)_
324
+ _See code: [src/commands/functions/env/list.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/functions/env/list.ts)_
325
325
 
326
326
  ## `sanity-run functions env remove NAME KEY`
327
327
 
@@ -342,7 +342,7 @@ EXAMPLES
342
342
  $ sanity-run functions env remove MyFunction API_URL
343
343
  ```
344
344
 
345
- _See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/functions/env/remove.ts)_
345
+ _See code: [src/commands/functions/env/remove.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/functions/env/remove.ts)_
346
346
 
347
347
  ## `sanity-run functions invoke NAME`
348
348
 
@@ -368,7 +368,7 @@ EXAMPLES
368
368
  $ sanity-run functions invoke <name> --file 'payload.json'
369
369
  ```
370
370
 
371
- _See code: [src/commands/functions/invoke.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/functions/invoke.ts)_
371
+ _See code: [src/commands/functions/invoke.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/functions/invoke.ts)_
372
372
 
373
373
  ## `sanity-run functions logs NAME`
374
374
 
@@ -400,7 +400,7 @@ EXAMPLES
400
400
  $ sanity-run functions logs <name> --delete
401
401
  ```
402
402
 
403
- _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/functions/logs.ts)_
403
+ _See code: [src/commands/functions/logs.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/functions/logs.ts)_
404
404
 
405
405
  ## `sanity-run functions test NAME`
406
406
 
@@ -433,7 +433,7 @@ EXAMPLES
433
433
  $ sanity-run functions test <name> --data '{ "id": 1 }' --timeout 60
434
434
  ```
435
435
 
436
- _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.3/src/commands/functions/test.ts)_
436
+ _See code: [src/commands/functions/test.ts](https://github.com/sanity-io/runtime-cli/blob/v4.3.5-bundle.0/src/commands/functions/test.ts)_
437
437
 
438
438
  ## `sanity-run help [COMMAND]`
439
439
 
@@ -6,5 +6,6 @@ export declare function stashAsset({ resource, auth, }: {
6
6
  }): Promise<{
7
7
  success: boolean;
8
8
  assetId?: string;
9
+ outputPath?: string;
9
10
  error?: string;
10
11
  }>;
@@ -3,21 +3,35 @@ import path from 'node:path';
3
3
  import { cwd } from 'node:process';
4
4
  import AdmZip from 'adm-zip';
5
5
  import config from '../../config.js';
6
+ import { bundleFunction } from '../../utils/bundle/bundle-function.js';
7
+ import { shouldBundleFunction } from '../../utils/functions/should-bundle.js';
6
8
  import getHeaders from '../../utils/get-headers.js';
7
9
  const { apiUrl } = config;
8
10
  export const stashUrl = `${apiUrl}vX/blueprints/assets/stash`;
9
11
  export async function stashAsset({ resource, auth, }) {
10
12
  if (!resource.src)
11
13
  throw new Error('Resource src is required');
14
+ let functionPath = path.join(cwd(), resource.src);
15
+ let cleanup = async () => { };
16
+ const shouldBundle = await shouldBundleFunction(resource);
17
+ if (shouldBundle) {
18
+ try {
19
+ const result = await bundleFunction(resource);
20
+ functionPath = result.outputDir;
21
+ cleanup = result.cleanup;
22
+ }
23
+ catch (err) {
24
+ return { success: false, error: err instanceof Error ? err.message : `${err}` };
25
+ }
26
+ }
12
27
  try {
13
- const sourcePath = path.join(cwd(), resource.src);
14
- const stats = await fs.promises.stat(sourcePath);
28
+ const stats = await fs.promises.stat(functionPath);
15
29
  const zip = new AdmZip();
16
30
  if (stats.isDirectory()) {
17
- zip.addLocalFolder(sourcePath);
31
+ zip.addLocalFolder(functionPath);
18
32
  }
19
33
  else {
20
- zip.addLocalFile(sourcePath, '', 'index.js');
34
+ zip.addLocalFile(functionPath, '', 'index.js');
21
35
  }
22
36
  const zipBuffer = zip.toBuffer();
23
37
  const base64Zip = zipBuffer.toString('base64');
@@ -41,4 +55,7 @@ export async function stashAsset({ resource, auth, }) {
41
55
  error = err.message;
42
56
  return { success: false, error };
43
57
  }
58
+ finally {
59
+ await cleanup();
60
+ }
44
61
  }
@@ -1,2 +1,2 @@
1
- import type { InvocationResponse, InvokeContextOptions, InvokePayloadOptions } from '../../utils/types.js';
2
- export declare function testAction(srcPath: string, options: InvokePayloadOptions, context: InvokeContextOptions): Promise<InvocationResponse>;
1
+ import type { InvocationResponse, InvokeContextOptions, InvokePayloadOptions, LocalFunctionResource } from '../../utils/types.js';
2
+ export declare function testAction(resource: LocalFunctionResource, options: InvokePayloadOptions, context: InvokeContextOptions): Promise<InvocationResponse>;
@@ -1,10 +1,10 @@
1
1
  import buildPayload from '../../utils/build-payload.js';
2
2
  import invoke from '../../utils/invoke-local.js';
3
- export async function testAction(srcPath, options, context) {
3
+ export async function testAction(resource, options, context) {
4
4
  const payload = buildPayload(options);
5
5
  const { timeout } = options;
6
6
  try {
7
- const { json, logs } = await invoke(srcPath, payload, context, timeout);
7
+ const { json, logs } = await invoke(resource, payload, context, timeout);
8
8
  return { error: undefined, json, logs };
9
9
  }
10
10
  catch (error) {
@@ -1,6 +1,5 @@
1
1
  import { Command } from '@oclif/core';
2
2
  export default class Config extends Command {
3
- token: string | undefined;
4
3
  static description: string;
5
4
  static examples: string[];
6
5
  static flags: {
@@ -9,6 +8,7 @@ export default class Config extends Command {
9
8
  'project-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
9
  'stack-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
10
  };
11
+ sanityToken: string | undefined;
12
12
  run(): Promise<void>;
13
13
  promptForProjectId({ knownProjectId }: {
14
14
  knownProjectId?: string;
@@ -8,7 +8,6 @@ import { getStack, listStacks } from '../../actions/blueprints/stacks.js';
8
8
  import { bold, dim, niceId } from '../../utils/display/colors.js';
9
9
  import { validTokenOrErrorMessage } from '../../utils/validated-token.js';
10
10
  export default class Config extends Command {
11
- token;
12
11
  static description = 'View or edit Blueprint configuration';
13
12
  static examples = [
14
13
  '<%= config.bin %> <%= command.id %>',
@@ -39,6 +38,7 @@ export default class Config extends Command {
39
38
  dependsOn: ['edit'],
40
39
  }),
41
40
  };
41
+ sanityToken;
42
42
  async run() {
43
43
  const { flags } = await this.parse(Config);
44
44
  const { edit: editConfig, 'project-id': editProjectId, 'stack-id': editStackId, 'test-config': testConfig, } = flags;
@@ -59,7 +59,7 @@ export default class Config extends Command {
59
59
  const { token, error: tokenErr } = await validTokenOrErrorMessage();
60
60
  if (tokenErr)
61
61
  this.error(tokenErr.message);
62
- this.token = token;
62
+ this.sanityToken = token;
63
63
  if (testConfig && !editConfig) {
64
64
  if (configStackId && configProjectId) {
65
65
  await this.testConfigAndReport({ stackId: configStackId, projectId: configProjectId });
@@ -96,9 +96,9 @@ export default class Config extends Command {
96
96
  }
97
97
  }
98
98
  async promptForProjectId({ knownProjectId }) {
99
- if (!this.token)
99
+ if (!this.sanityToken)
100
100
  this.error('Unable to list projects. Missing API token.');
101
- const { ok, projects, error } = await listProjects({ token: this.token });
101
+ const { ok, projects, error } = await listProjects({ token: this.sanityToken });
102
102
  if (!ok)
103
103
  this.error(error ?? 'Unknown error listing projects');
104
104
  if (projects.length === 0) {
@@ -120,9 +120,9 @@ export default class Config extends Command {
120
120
  return pickedProjectId;
121
121
  }
122
122
  async promptForStackId({ projectId, knownStackId, }) {
123
- if (!this.token)
123
+ if (!this.sanityToken)
124
124
  this.error('Unable to list Stacks. Missing API token.');
125
- const auth = { token: this.token, projectId };
125
+ const auth = { token: this.sanityToken, projectId };
126
126
  // get stacks for selected project
127
127
  const { ok: stacksOk, stacks, error: stacksError } = await listStacks(auth);
128
128
  if (!stacksOk)
@@ -147,12 +147,12 @@ export default class Config extends Command {
147
147
  return undefined;
148
148
  }
149
149
  async testConfigAndReport({ stackId, projectId }) {
150
- if (!this.token)
150
+ if (!this.sanityToken)
151
151
  this.error('Unable to test the configuration. Missing API token.');
152
152
  const spinner = Spinner({ text: 'Testing the configuration...' }).start();
153
153
  const { ok, error } = await getStack({
154
154
  stackId,
155
- auth: { token: this.token, projectId },
155
+ auth: { token: this.sanityToken, projectId },
156
156
  });
157
157
  if (!ok) {
158
158
  spinner.error(error ?? 'Unknown error testing the configuration');
@@ -1,4 +1,5 @@
1
1
  import { setTimeout } from 'node:timers/promises';
2
+ import { inspect } from 'node:util';
2
3
  import { Command, Flags } from '@oclif/core';
3
4
  import Spinner from 'yocto-spinner';
4
5
  import { stashAsset } from '../../actions/blueprints/assets.js';
@@ -24,9 +25,7 @@ export default class Deploy extends Command {
24
25
  const { errors, projectId, stackId, parsedBlueprint: { resources }, deployedStack, } = await readBlueprintOnDisk({ getStack: true, token });
25
26
  if (errors.length > 0) {
26
27
  // printErrors(errors) // TODO: error printer in formatting
27
- this.log('Blueprint parse errors:');
28
- console.dir(errors, { depth: null });
29
- return;
28
+ this.error(`Blueprint parse errors:\n${inspect(errors, { depth: null })}`);
30
29
  }
31
30
  if (!deployedStack || !stackId || !projectId) {
32
31
  this.error('Before deploying, run `sanity blueprints init`');
@@ -96,7 +95,7 @@ export default class Deploy extends Command {
96
95
  }
97
96
  else {
98
97
  this.debug('STACK ERROR RESPONSE:', stack);
99
- spinner.error(`${red('Failed')} to ${deployedStack ? 'update' : 'create'} stack`);
98
+ spinner.error(`${red('Failed')} to update stack`);
100
99
  this.log(`Error: ${deployError || JSON.stringify(stack, null, 2) || 'Unknown error'}`);
101
100
  }
102
101
  }
@@ -9,7 +9,7 @@ export default class Init extends Command {
9
9
  'stack-id': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
10
10
  'stack-name': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
11
  };
12
- token: string | undefined;
12
+ sanityToken: string | undefined;
13
13
  run(): Promise<void>;
14
14
  promptForBlueprintType(): Promise<string>;
15
15
  promptForProjectId(): Promise<string>;
@@ -39,7 +39,7 @@ export default class Init extends Command {
39
39
  exclusive: ['stack-id'],
40
40
  }),
41
41
  };
42
- token;
42
+ sanityToken;
43
43
  async run() {
44
44
  const { flags } = await this.parse(Init);
45
45
  const { 'blueprint-type': flagBlueprintType, 'project-id': flagProjectId, 'stack-id': flagStackId, 'stack-name': flagStackName, } = flags;
@@ -50,7 +50,7 @@ export default class Init extends Command {
50
50
  const { token, error: tokenErr } = await validTokenOrErrorMessage();
51
51
  if (tokenErr)
52
52
  this.error(tokenErr.message);
53
- this.token = token;
53
+ this.sanityToken = token;
54
54
  const blueprintExtension = flagBlueprintType || (await this.promptForBlueprintType());
55
55
  if (!blueprintExtension)
56
56
  this.error('Blueprint type is required.');
@@ -62,7 +62,7 @@ export default class Init extends Command {
62
62
  if (flagStackName) {
63
63
  const stack = await this.createEmptyStack({
64
64
  stackPayload: { name: flagStackName, projectId, document: { resources: [] } },
65
- auth: { token: this.token, projectId },
65
+ auth: { token: this.sanityToken, projectId },
66
66
  });
67
67
  stackId = stack.id;
68
68
  }
@@ -97,9 +97,9 @@ export default class Init extends Command {
97
97
  return pickedBlueprintsType;
98
98
  }
99
99
  async promptForProjectId() {
100
- if (!this.token)
100
+ if (!this.sanityToken)
101
101
  this.error('Unable to list projects. Missing API token.');
102
- const { ok: projectsOk, error: projectsErr, projects } = await listProjects({ token: this.token });
102
+ const { ok: projectsOk, error: projectsErr, projects, } = await listProjects({ token: this.sanityToken });
103
103
  if (!projectsOk)
104
104
  this.error(projectsErr ?? 'Unknown error listing projects');
105
105
  if (projects.length === 0) {
@@ -120,9 +120,9 @@ export default class Init extends Command {
120
120
  return pickedProjectId;
121
121
  }
122
122
  async promptForStackId({ projectId }) {
123
- if (!this.token)
123
+ if (!this.sanityToken)
124
124
  this.error('Unable to list Stacks. Missing API token.');
125
- const { ok: stacksOk, error: stacksErr, stacks, } = await listStacks({ token: this.token, projectId });
125
+ const { ok: stacksOk, error: stacksErr, stacks, } = await listStacks({ token: this.sanityToken, projectId });
126
126
  if (!stacksOk)
127
127
  this.error(stacksErr || 'Failed to list Stacks');
128
128
  const stackChoices = [{ name: bold('✨ Create a new Stack'), value: 'new' }];
@@ -152,7 +152,7 @@ export default class Init extends Command {
152
152
  ]);
153
153
  const stack = await this.createEmptyStack({
154
154
  stackPayload: { name: stackName, projectId, document: { resources: [] } },
155
- auth: { token: this.token, projectId },
155
+ auth: { token: this.sanityToken, projectId },
156
156
  });
157
157
  return stack.id;
158
158
  }
@@ -18,7 +18,7 @@ export default class Logs extends Command {
18
18
  delete: import("@oclif/core/interfaces").BooleanFlag<boolean>;
19
19
  force: import("@oclif/core/interfaces").BooleanFlag<boolean>;
20
20
  };
21
- token: string | undefined;
21
+ sanityToken: string | undefined;
22
22
  run(): Promise<void>;
23
23
  runDeleteLogs(name: string, options: RunDeleteOptions): Promise<void>;
24
24
  runGetLogs(name: string, options: RunGetOptions): Promise<void>;
@@ -52,12 +52,12 @@ export default class Logs extends Command {
52
52
  required: false,
53
53
  }),
54
54
  };
55
- token;
55
+ sanityToken;
56
56
  async run() {
57
57
  const { token, error: tokenErr } = await validTokenOrErrorMessage();
58
58
  if (tokenErr)
59
59
  this.error(tokenErr.message);
60
- this.token = token;
60
+ this.sanityToken = token;
61
61
  const { args, flags } = await this.parse(Logs);
62
62
  if (flags.delete === true) {
63
63
  await this.runDeleteLogs(args.name, flags);
@@ -81,10 +81,10 @@ export default class Logs extends Command {
81
81
  if (!projectId || !externalId) {
82
82
  this.error('Stack not found');
83
83
  }
84
- if (!this.token)
84
+ if (!this.sanityToken)
85
85
  this.error('Unable to delete logs. Missing API token.');
86
86
  const spinner = Spinner({ text: `Deleting logs for function ${yellow(name)}` }).start();
87
- const { ok, error } = await deleteLogsAction(externalId, { token: this.token, projectId });
87
+ const { ok, error } = await deleteLogsAction(externalId, { token: this.sanityToken, projectId });
88
88
  if (!ok) {
89
89
  spinner.error(`${red('Failed')} to retrieve logs`);
90
90
  this.log(`Error: ${error || 'Unknown error'}`);
@@ -98,9 +98,9 @@ export default class Logs extends Command {
98
98
  if (!projectId || !externalId) {
99
99
  this.error('Stack not found');
100
100
  }
101
- if (!this.token)
101
+ if (!this.sanityToken)
102
102
  this.error('Unable to retrieve logs. Missing API token.');
103
- const { ok, error, logs, total } = await logsAction(externalId, { limit: options.limit }, { token: this.token, projectId });
103
+ const { ok, error, logs, total } = await logsAction(externalId, { limit: options.limit }, { token: this.sanityToken, projectId });
104
104
  if (!ok) {
105
105
  spinner.error(`${red('Failed')} to retrieve logs`);
106
106
  this.log(`Error: ${error || 'Unknown error'}`);
@@ -129,9 +129,9 @@ export default class Logs extends Command {
129
129
  }
130
130
  }
131
131
  async getProjectAndExternalId(name) {
132
- if (!this.token)
132
+ if (!this.sanityToken)
133
133
  this.error('Missing API token.');
134
- const { deployedStack } = await readBlueprintOnDisk({ getStack: true, token: this.token });
134
+ const { deployedStack } = await readBlueprintOnDisk({ getStack: true, token: this.sanityToken });
135
135
  if (!deployedStack) {
136
136
  return {};
137
137
  }
@@ -1,7 +1,7 @@
1
1
  import { Args, Command, Flags } from '@oclif/core';
2
2
  import { readBlueprintOnDisk } from '../../actions/blueprints/blueprint.js';
3
3
  import { testAction } from '../../actions/functions/test.js';
4
- import { getFunctionSource } from '../../utils/find-function.js';
4
+ import { findFunctionByName } from '../../utils/find-function.js';
5
5
  export default class Test extends Command {
6
6
  static args = {
7
7
  name: Args.string({ description: 'The name of the Sanity Function', required: true }),
@@ -42,11 +42,8 @@ export default class Test extends Command {
42
42
  const { args, flags } = await this.parse(Test);
43
43
  const { parsedBlueprint } = await readBlueprintOnDisk({ getStack: false });
44
44
  try {
45
- const src = getFunctionSource(parsedBlueprint, args.name);
46
- if (!src) {
47
- this.error(`Error: Function ${args.name} has no source code`);
48
- }
49
- const { json, logs, error } = await testAction(src, {
45
+ const resource = findFunctionByName(parsedBlueprint, args.name);
46
+ const { json, logs, error } = await testAction(resource, {
50
47
  data: flags.data,
51
48
  file: flags.file,
52
49
  timeout: flags.timeout,
@@ -1,9 +1,11 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
+ import * as http from 'node:http';
2
3
  import { default as mime } from 'mime-types';
3
4
  import { readBlueprintOnDisk } from '../actions/blueprints/blueprint.js';
4
5
  import config from '../config.js';
6
+ import { findFunctionByName } from '../utils/find-function.js';
5
7
  import invoke from '../utils/invoke-local.js';
6
- import * as http from 'node:http';
8
+ import { isRecord } from '../utils/is-record.js';
7
9
  const host = 'localhost';
8
10
  const app = (port) => {
9
11
  const requestListener = async (req, res) => {
@@ -14,30 +16,40 @@ const app = (port) => {
14
16
  const { parsedBlueprint } = await readBlueprintOnDisk({ getStack: false });
15
17
  res.setHeader('Content-Type', 'application/json');
16
18
  res.writeHead(200);
17
- res.end(JSON.stringify(parsedBlueprint));
19
+ res.end(JSON.stringify(parsedBlueprint)); // Use parsedBlueprint directly
18
20
  }
19
- catch {
21
+ catch (error) {
20
22
  res.writeHead(404);
21
- res.end();
23
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'Unknown error' }));
22
24
  }
23
25
  break;
24
26
  }
25
27
  case req.url === '/invoke': {
26
28
  if (req.method === 'POST') {
27
- let body = '';
28
- req.on('data', (data) => {
29
- body += data;
30
- });
29
+ const body = [];
30
+ req.on('data', (data) => body.push(data));
31
31
  req.on('end', async () => {
32
- const { data, func } = JSON.parse(body);
33
- const { context, event } = data;
34
32
  res.setHeader('Content-Type', 'application/json');
35
33
  try {
36
- const response = await invoke(func, event, context);
37
- res.writeHead(200);
34
+ const { data, func: functionName } = parseInvokeRequest(Buffer.concat(body));
35
+ const { context, event } = data;
36
+ const start = performance.now();
37
+ const { parsedBlueprint } = await readBlueprintOnDisk({ getStack: false });
38
+ const resource = findFunctionByName(parsedBlueprint, functionName);
39
+ const readBlueprintTime = performance.now() - start;
40
+ const response = await invoke(resource, event, context);
41
+ const timings = { ...response.timings, 'blueprint:read': readBlueprintTime };
42
+ const timingHeaders = [];
43
+ for (const [key, value] of Object.entries(timings)) {
44
+ timingHeaders.push(`${key.replace(/:/g, '-')};dur=${Math.abs(value).toFixed(1)}`);
45
+ }
46
+ if (timingHeaders.length > 0) {
47
+ res.setHeader('Server-Timing', timingHeaders.join(', '));
48
+ }
38
49
  res.end(JSON.stringify(response));
39
50
  }
40
51
  catch (error) {
52
+ console.error(error);
41
53
  const response = { logs: '', error: '' };
42
54
  if (error instanceof Error) {
43
55
  response.logs = error.message;
@@ -112,4 +124,60 @@ const app = (port) => {
112
124
  const server = http.createServer(requestListener);
113
125
  server.listen(port, host, () => { });
114
126
  };
127
+ function parseInvokeRequest(body) {
128
+ let json;
129
+ try {
130
+ json = JSON.parse(body.toString('utf8'));
131
+ }
132
+ catch (error) {
133
+ throw new Error('Request body is not valid JSON', { cause: error });
134
+ }
135
+ if (!isRecord(json)) {
136
+ throw new Error('Request body is not valid, must be an object');
137
+ }
138
+ if (!('func' in json)) {
139
+ throw new Error('Request body is not valid, missing `func` field');
140
+ }
141
+ if (!('data' in json)) {
142
+ throw new Error('Request body is not valid, missing `data` field');
143
+ }
144
+ const { data, func } = json;
145
+ if (typeof func !== 'string') {
146
+ throw new Error('Request body is not valid, `func` field is not a string');
147
+ }
148
+ if (!isRecord(data)) {
149
+ throw new Error('Request body is not valid, `data` field is not an object');
150
+ }
151
+ const { context, event } = data;
152
+ if (!isRecord(context)) {
153
+ throw new Error('Request body is not valid, `context` field is not an object');
154
+ }
155
+ if (!isRecord(event)) {
156
+ throw new Error('Request body is not valid, `event` field is not an object');
157
+ }
158
+ if (!('clientOptions' in context)) {
159
+ throw new Error('Request body is not valid, `context.clientOptions` field is missing');
160
+ }
161
+ if (!isRecord(context.clientOptions)) {
162
+ throw new Error('Request body is not valid, `context.clientOptions` field is not an object');
163
+ }
164
+ const { projectId, dataset, apiVersion } = context.clientOptions;
165
+ if (typeof projectId !== 'string' && typeof projectId !== 'undefined') {
166
+ throw new Error('Request body is not valid, `context.clientOptions.projectId` field is not a string');
167
+ }
168
+ if (typeof dataset !== 'string' && typeof dataset !== 'undefined') {
169
+ throw new Error('Request body is not valid, `context.clientOptions.dataset` field is not a string');
170
+ }
171
+ if (typeof apiVersion !== 'string' && typeof apiVersion !== 'undefined') {
172
+ throw new Error('Request body is not valid, `context.clientOptions.apiVersion` field is not a string');
173
+ }
174
+ const clientOptions = {
175
+ ...context.clientOptions,
176
+ projectId,
177
+ dataset,
178
+ // Prefer `undefined` over empty string, triggering the right warnings in the client
179
+ apiVersion: apiVersion || undefined,
180
+ };
181
+ return { func, data: { context: { ...context, clientOptions }, event } };
182
+ }
115
183
  export default app;