@plasmicapp/cli 0.1.185 → 0.1.187

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.
@@ -1,6 +1,8 @@
1
- export interface LocalizationStringsArgs {
1
+ import { CommonArgs } from "..";
2
+ export interface LocalizationStringsArgs extends CommonArgs {
2
3
  host: string;
3
4
  projects: readonly string[];
5
+ projectTokens?: readonly string[];
4
6
  format: "po" | "json" | "lingui";
5
7
  output: string;
6
8
  forceOverwrite: boolean;
@@ -14,31 +14,59 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.localizationStrings = void 0;
16
16
  const chalk_1 = __importDefault(require("chalk"));
17
+ const lodash_1 = require("lodash");
17
18
  const api_1 = require("../api");
18
19
  const deps_1 = require("../deps");
19
20
  const lib_1 = require("../lib");
20
21
  const auth_utils_1 = require("../utils/auth-utils");
21
22
  const config_utils_1 = require("../utils/config-utils");
22
23
  const file_utils_1 = require("../utils/file-utils");
24
+ const get_context_1 = require("../utils/get-context");
23
25
  const user_utils_1 = require("../utils/user-utils");
24
26
  function localizationStrings(opts) {
27
+ var _a;
25
28
  return __awaiter(this, void 0, void 0, function* () {
26
29
  if (!opts.projects || opts.projects.length === 0) {
27
30
  throw new lib_1.HandledError(`Missing projects.`);
28
31
  }
32
+ if (!opts.baseDir)
33
+ opts.baseDir = process.cwd();
34
+ const parsedProjectTokens = ((_a = opts.projectTokens) !== null && _a !== void 0 ? _a : []).map((val) => {
35
+ const [projectId, projectApiToken] = val.split(":");
36
+ if (!projectId || !projectApiToken) {
37
+ throw new Error(`Invalid value passed to '--project-tokens': ${val}\nPlease provide the API tokens with the format PROJECT_ID:PROJECT_API_TOKEN`);
38
+ }
39
+ return {
40
+ projectId: projectId.trim(),
41
+ projectApiToken: projectApiToken.trim(),
42
+ };
43
+ });
29
44
  const output = !opts.output
30
45
  ? opts.format === "po"
31
46
  ? "data.po"
32
47
  : "data.json"
33
48
  : opts.output;
34
- const auth = yield auth_utils_1.getOrStartAuth({
35
- baseDir: "",
36
- host: opts.host || config_utils_1.DEFAULT_HOST,
37
- });
38
- if (auth) {
39
- const api = new api_1.PlasmicApi(auth);
49
+ const projectTokensFromConfig = [];
50
+ const auth = yield auth_utils_1.getCurrentAuth(opts.auth);
51
+ const maybeConfigFile = opts.config || config_utils_1.findConfigFile(opts.baseDir, { traverseParents: true });
52
+ if (maybeConfigFile) {
53
+ const context = yield get_context_1.getContext(opts, { enableSkipAuth: true });
54
+ context.config.projects.forEach((p) => {
55
+ projectTokensFromConfig.push(lodash_1.pick(p, "projectId", "projectApiToken"));
56
+ });
57
+ }
58
+ const projectIdsAndTokens = [
59
+ ...parsedProjectTokens,
60
+ ...projectTokensFromConfig,
61
+ ].filter((v) => !!v && !!v.projectId && !!v.projectApiToken);
62
+ if (auth || projectIdsAndTokens.length > 0) {
63
+ const api = new api_1.PlasmicApi(auth !== null && auth !== void 0 ? auth : {
64
+ host: config_utils_1.DEFAULT_HOST,
65
+ user: "",
66
+ token: "",
67
+ });
40
68
  deps_1.logger.info(`Generating localization strings for ${chalk_1.default.bold(opts.projects.join(", "))}...`);
41
- const data = yield api.genLocalizationStrings(opts.projects, opts.format);
69
+ const data = yield api.genLocalizationStrings(opts.projects, opts.format, projectIdsAndTokens);
42
70
  if (file_utils_1.existsBuffered(output)) {
43
71
  const overwrite = yield user_utils_1.confirmWithUser(`File ${output} already exists. Do you want to overwrite?`, opts.forceOverwrite);
44
72
  if (!overwrite) {
@@ -49,7 +77,10 @@ function localizationStrings(opts) {
49
77
  deps_1.logger.info(`Localization strings have been written to ${output}`);
50
78
  }
51
79
  else {
52
- deps_1.logger.error("Missing auth information");
80
+ deps_1.logger.error(`Missing auth information. You can follow any of the steps below to fix it:
81
+ - Run 'plasmic auth'
82
+ - Provide the project API token to 'plasmic.json'
83
+ - Or provide the project API token through '--project-tokens' flag`);
53
84
  }
54
85
  });
55
86
  }
@@ -1,3 +1,3 @@
1
1
  import { StyleTokensMap } from "../api";
2
2
  import { PlasmicContext } from "../utils/config-utils";
3
- export declare function upsertStyleTokens(context: PlasmicContext, newStyleMap: StyleTokensMap): Promise<void>;
3
+ export declare function upsertStyleTokens(context: PlasmicContext, newStyleMap: StyleTokensMap, projectId: string): Promise<void>;
@@ -12,7 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.upsertStyleTokens = void 0;
13
13
  const error_1 = require("../utils/error");
14
14
  const file_utils_1 = require("../utils/file-utils");
15
- function upsertStyleTokens(context, newStyleMap) {
15
+ function upsertStyleTokens(context, newStyleMap, projectId) {
16
16
  return __awaiter(this, void 0, void 0, function* () {
17
17
  const curStyleMap = yield readCurStyleMap(context);
18
18
  for (const prop of newStyleMap.props) {
@@ -24,6 +24,19 @@ function upsertStyleTokens(context, newStyleMap) {
24
24
  curStyleMap.props.push(prop);
25
25
  }
26
26
  }
27
+ const allNewPropIds = new Set(newStyleMap.props.map((prop) => prop.meta.id));
28
+ curStyleMap.props = curStyleMap.props.filter((prop) => {
29
+ if (prop.meta.projectId !== projectId) {
30
+ // Keep all tokens from other projects
31
+ return true;
32
+ }
33
+ if (allNewPropIds.has(prop.meta.id)) {
34
+ // Keep the current tokens in this project
35
+ return true;
36
+ }
37
+ // Delete the tokens that have been removed from the project
38
+ return false;
39
+ });
27
40
  curStyleMap.props.sort((prop1, prop2) => prop1.name === prop2.name ? 0 : prop1.name < prop2.name ? -1 : 1);
28
41
  yield file_utils_1.writeFileContent(context, context.config.tokens.tokensFilePath, JSON.stringify(curStyleMap, undefined, 2), { force: true });
29
42
  });
@@ -381,7 +381,7 @@ function syncProject(context, opts, projectIdsAndTokens, projectId, componentIds
381
381
  yield sync_global_variants_1.syncGlobalVariants(context, projectBundle.projectConfig, projectBundle.globalVariants, projectBundle.checksums, opts.baseDir);
382
382
  yield syncProjectConfig(context, projectBundle.projectConfig, projectApiToken, projectVersion, dependencies, projectBundle.components, opts.forceOverwrite, !!opts.appendJsxOnMissingBase, summary, pendingMerge, projectBundle.checksums, opts.baseDir, indirect);
383
383
  syncCodeComponentsMeta(context, projectId, projectBundle.codeComponentMetas);
384
- yield sync_styles_1.upsertStyleTokens(context, projectBundle.usedTokens);
384
+ yield sync_styles_1.upsertStyleTokens(context, projectBundle.usedTokens, projectBundle.projectConfig.projectId);
385
385
  yield sync_icons_1.syncProjectIconAssets(context, projectId, projectVersion, projectBundle.iconAssets, projectBundle.checksums, opts.baseDir);
386
386
  yield sync_images_1.syncProjectImageAssets(context, projectId, projectVersion, projectBundle.imageAssets, projectBundle.checksums);
387
387
  (projectBundle.usedNpmPackages || []).forEach((pkg) => externalNpmPackages.add(pkg));
package/dist/api.d.ts CHANGED
@@ -189,7 +189,7 @@ export declare class PlasmicApi {
189
189
  metadata?: Metadata;
190
190
  }): Promise<ProjectBundle>;
191
191
  projectMeta(projectId: string): Promise<ProjectMetaInfo>;
192
- genLocalizationStrings(projects: readonly string[], format: "po" | "json" | "lingui"): Promise<string>;
192
+ genLocalizationStrings(projects: readonly string[], format: "po" | "json" | "lingui", projectIdsAndTokens: ProjectIdAndToken[]): Promise<string>;
193
193
  uploadBundle(projectId: string, bundleName: string, bundleJs: string, css: string[], metaJson: string, genModulePath: string | undefined, genCssPaths: string[], pkgVersion: string | undefined, extraPropMetaJson: string | undefined, themeProviderWrapper: string | undefined, themeModule: string | undefined): Promise<StyleTokensMap>;
194
194
  projectStyleTokens(projectId: string, versionRange?: string): Promise<StyleTokensMap>;
195
195
  projectIcons(projectId: string, versionRange?: string, iconIds?: string[]): Promise<ProjectIconsResponse>;
package/dist/api.js CHANGED
@@ -99,11 +99,15 @@ class PlasmicApi {
99
99
  return result.data;
100
100
  });
101
101
  }
102
- genLocalizationStrings(projects, format) {
102
+ genLocalizationStrings(projects, format, projectIdsAndTokens) {
103
103
  return __awaiter(this, void 0, void 0, function* () {
104
104
  const result = yield this.get(`${this.codegenHost}/api/v1/localization/gen-texts?format=${format}&preview=true&${projects
105
105
  .map((p) => `projectId=${p}`)
106
- .join("&")}`);
106
+ .join("&")}`, undefined, {
107
+ "x-plasmic-api-project-tokens": projectIdsAndTokens
108
+ .map(({ projectId, projectApiToken }) => `${projectId}:${projectApiToken}`)
109
+ .join(","),
110
+ });
107
111
  return result.data;
108
112
  });
109
113
  }
@@ -176,11 +180,11 @@ class PlasmicApi {
176
180
  }
177
181
  });
178
182
  }
179
- get(url, rethrowAppError) {
183
+ get(url, rethrowAppError, extraHeaders) {
180
184
  return __awaiter(this, void 0, void 0, function* () {
181
185
  try {
182
186
  return yield axios_1.default.get(url, {
183
- headers: this.makeHeaders(),
187
+ headers: Object.assign(Object.assign({}, this.makeHeaders()), (extraHeaders !== null && extraHeaders !== void 0 ? extraHeaders : {})),
184
188
  });
185
189
  }
186
190
  catch (e) {
package/dist/index.js CHANGED
@@ -213,6 +213,11 @@ yargs_1.default
213
213
  type: "boolean",
214
214
  describe: "Overwrite the output file.",
215
215
  default: false,
216
+ })
217
+ .option("project-tokens", {
218
+ type: "array",
219
+ default: [],
220
+ describe: "(Optional) List of project API tokens to be used for auth, in the format PROJECT_ID:PROJECT_API_TOKEN (the pairs should be separated by comma)",
216
221
  }), (argv) => error_1.handleError(localization_strings_1.localizationStrings(argv)))
217
222
  .demandCommand()
218
223
  .strict()
@@ -155,7 +155,9 @@ function findInstalledPackageJsonFile(context, pkg) {
155
155
  const rootDir = packageJsonPath
156
156
  ? path_1.default.dirname(packageJsonPath)
157
157
  : context.rootDir;
158
- const files = fast_glob_1.default.sync(`${rootDir}/**/node_modules/${pkg}/package.json`);
158
+ const files = fast_glob_1.default.sync(`${rootDir}/**/node_modules/${pkg}/package.json`, {
159
+ ignore: [`**/node_modules/**/node_modules/**`],
160
+ });
159
161
  return files.length > 0 ? files[0] : undefined;
160
162
  }
161
163
  function parsePackageJson(path) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@plasmicapp/cli",
3
- "version": "0.1.185",
3
+ "version": "0.1.187",
4
4
  "description": "plasmic cli for syncing local code with Plasmic designs",
5
5
  "engines": {
6
6
  "node": ">=12"
@@ -1,15 +1,23 @@
1
1
  import chalk from "chalk";
2
- import { PlasmicApi } from "../api";
2
+ import { pick } from "lodash";
3
+ import { CommonArgs } from "..";
4
+ import { PlasmicApi, ProjectIdAndToken } from "../api";
3
5
  import { logger } from "../deps";
4
6
  import { HandledError } from "../lib";
5
- import { getOrStartAuth } from "../utils/auth-utils";
6
- import { DEFAULT_HOST } from "../utils/config-utils";
7
+ import { getCurrentAuth, getOrStartAuth } from "../utils/auth-utils";
8
+ import {
9
+ DEFAULT_HOST,
10
+ findConfigFile,
11
+ PlasmicContext,
12
+ } from "../utils/config-utils";
7
13
  import { existsBuffered, writeFileText } from "../utils/file-utils";
14
+ import { getContext } from "../utils/get-context";
8
15
  import { confirmWithUser } from "../utils/user-utils";
9
16
 
10
- export interface LocalizationStringsArgs {
17
+ export interface LocalizationStringsArgs extends CommonArgs {
11
18
  host: string;
12
19
  projects: readonly string[];
20
+ projectTokens?: readonly string[];
13
21
  format: "po" | "json" | "lingui";
14
22
  output: string;
15
23
  forceOverwrite: boolean;
@@ -21,23 +29,60 @@ export async function localizationStrings(
21
29
  if (!opts.projects || opts.projects.length === 0) {
22
30
  throw new HandledError(`Missing projects.`);
23
31
  }
32
+ if (!opts.baseDir) opts.baseDir = process.cwd();
33
+ const parsedProjectTokens: ProjectIdAndToken[] = (
34
+ opts.projectTokens ?? []
35
+ ).map((val) => {
36
+ const [projectId, projectApiToken] = val.split(":");
37
+ if (!projectId || !projectApiToken) {
38
+ throw new Error(
39
+ `Invalid value passed to '--project-tokens': ${val}\nPlease provide the API tokens with the format PROJECT_ID:PROJECT_API_TOKEN`
40
+ );
41
+ }
42
+ return {
43
+ projectId: projectId.trim(),
44
+ projectApiToken: projectApiToken.trim(),
45
+ };
46
+ });
24
47
  const output = !opts.output
25
48
  ? opts.format === "po"
26
49
  ? "data.po"
27
50
  : "data.json"
28
51
  : opts.output;
29
- const auth = await getOrStartAuth({
30
- baseDir: "",
31
- host: opts.host || DEFAULT_HOST,
32
- });
33
- if (auth) {
34
- const api = new PlasmicApi(auth);
52
+ const projectTokensFromConfig: ProjectIdAndToken[] = [];
53
+ const auth = await getCurrentAuth(opts.auth);
54
+ const maybeConfigFile =
55
+ opts.config || findConfigFile(opts.baseDir, { traverseParents: true });
56
+ if (maybeConfigFile) {
57
+ const context = await getContext(opts, { enableSkipAuth: true });
58
+ context.config.projects.forEach((p) => {
59
+ projectTokensFromConfig.push(pick(p, "projectId", "projectApiToken"));
60
+ });
61
+ }
62
+
63
+ const projectIdsAndTokens = [
64
+ ...parsedProjectTokens,
65
+ ...projectTokensFromConfig,
66
+ ].filter((v) => !!v && !!v.projectId && !!v.projectApiToken);
67
+
68
+ if (auth || projectIdsAndTokens.length > 0) {
69
+ const api = new PlasmicApi(
70
+ auth ?? {
71
+ host: DEFAULT_HOST,
72
+ user: "",
73
+ token: "",
74
+ }
75
+ );
35
76
  logger.info(
36
77
  `Generating localization strings for ${chalk.bold(
37
78
  opts.projects.join(", ")
38
79
  )}...`
39
80
  );
40
- const data = await api.genLocalizationStrings(opts.projects, opts.format);
81
+ const data = await api.genLocalizationStrings(
82
+ opts.projects,
83
+ opts.format,
84
+ projectIdsAndTokens
85
+ );
41
86
  if (existsBuffered(output)) {
42
87
  const overwrite = await confirmWithUser(
43
88
  `File ${output} already exists. Do you want to overwrite?`,
@@ -52,6 +97,9 @@ export async function localizationStrings(
52
97
  writeFileText(output, data);
53
98
  logger.info(`Localization strings have been written to ${output}`);
54
99
  } else {
55
- logger.error("Missing auth information");
100
+ logger.error(`Missing auth information. You can follow any of the steps below to fix it:
101
+ - Run 'plasmic auth'
102
+ - Provide the project API token to 'plasmic.json'
103
+ - Or provide the project API token through '--project-tokens' flag`);
56
104
  }
57
105
  }
@@ -9,7 +9,8 @@ import {
9
9
 
10
10
  export async function upsertStyleTokens(
11
11
  context: PlasmicContext,
12
- newStyleMap: StyleTokensMap
12
+ newStyleMap: StyleTokensMap,
13
+ projectId: string
13
14
  ) {
14
15
  const curStyleMap = await readCurStyleMap(context);
15
16
  for (const prop of newStyleMap.props) {
@@ -22,6 +23,19 @@ export async function upsertStyleTokens(
22
23
  curStyleMap.props.push(prop);
23
24
  }
24
25
  }
26
+ const allNewPropIds = new Set(newStyleMap.props.map((prop) => prop.meta.id));
27
+ curStyleMap.props = curStyleMap.props.filter((prop) => {
28
+ if (prop.meta.projectId !== projectId) {
29
+ // Keep all tokens from other projects
30
+ return true;
31
+ }
32
+ if (allNewPropIds.has(prop.meta.id)) {
33
+ // Keep the current tokens in this project
34
+ return true;
35
+ }
36
+ // Delete the tokens that have been removed from the project
37
+ return false;
38
+ });
25
39
  curStyleMap.props.sort((prop1, prop2) =>
26
40
  prop1.name === prop2.name ? 0 : prop1.name < prop2.name ? -1 : 1
27
41
  );
@@ -672,7 +672,11 @@ async function syncProject(
672
672
  indirect
673
673
  );
674
674
  syncCodeComponentsMeta(context, projectId, projectBundle.codeComponentMetas);
675
- await upsertStyleTokens(context, projectBundle.usedTokens);
675
+ await upsertStyleTokens(
676
+ context,
677
+ projectBundle.usedTokens,
678
+ projectBundle.projectConfig.projectId
679
+ );
676
680
  await syncProjectIconAssets(
677
681
  context,
678
682
  projectId,
package/src/api.ts CHANGED
@@ -289,14 +289,24 @@ export class PlasmicApi {
289
289
 
290
290
  async genLocalizationStrings(
291
291
  projects: readonly string[],
292
- format: "po" | "json" | "lingui"
292
+ format: "po" | "json" | "lingui",
293
+ projectIdsAndTokens: ProjectIdAndToken[]
293
294
  ) {
294
295
  const result = await this.get(
295
296
  `${
296
297
  this.codegenHost
297
298
  }/api/v1/localization/gen-texts?format=${format}&preview=true&${projects
298
299
  .map((p) => `projectId=${p}`)
299
- .join("&")}`
300
+ .join("&")}`,
301
+ undefined,
302
+ {
303
+ "x-plasmic-api-project-tokens": projectIdsAndTokens
304
+ .map(
305
+ ({ projectId, projectApiToken }) =>
306
+ `${projectId}:${projectApiToken}`
307
+ )
308
+ .join(","),
309
+ }
300
310
  );
301
311
  return result.data as string;
302
312
  }
@@ -408,10 +418,10 @@ export class PlasmicApi {
408
418
  }
409
419
  }
410
420
 
411
- private async get(url: string, rethrowAppError?: boolean) {
421
+ private async get(url: string, rethrowAppError?: boolean, extraHeaders?: {}) {
412
422
  try {
413
423
  return await axios.get(url, {
414
- headers: this.makeHeaders(),
424
+ headers: { ...this.makeHeaders(), ...(extraHeaders ?? {}) },
415
425
  });
416
426
  } catch (e) {
417
427
  const error = e as AxiosError;
package/src/index.ts CHANGED
@@ -261,6 +261,12 @@ yargs
261
261
  type: "boolean",
262
262
  describe: "Overwrite the output file.",
263
263
  default: false,
264
+ })
265
+ .option("project-tokens", {
266
+ type: "array",
267
+ default: [],
268
+ describe:
269
+ "(Optional) List of project API tokens to be used for auth, in the format PROJECT_ID:PROJECT_API_TOKEN (the pairs should be separated by comma)",
264
270
  }),
265
271
  (argv) => handleError(localizationStrings(argv))
266
272
  )
@@ -169,7 +169,9 @@ function findInstalledPackageJsonFile(context: PlasmicContext, pkg: string) {
169
169
  const rootDir = packageJsonPath
170
170
  ? path.dirname(packageJsonPath)
171
171
  : context.rootDir;
172
- const files = glob.sync(`${rootDir}/**/node_modules/${pkg}/package.json`);
172
+ const files = glob.sync(`${rootDir}/**/node_modules/${pkg}/package.json`, {
173
+ ignore: [`**/node_modules/**/node_modules/**`],
174
+ });
173
175
  return files.length > 0 ? files[0] : undefined;
174
176
  }
175
177