@angular-devkit/core#json TypeScript Examples

The following examples show how to use @angular-devkit/core#json. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
async addPageEntry(list: string[]) {
    const configPath = join(normalize(this.root()), 'src', 'app.json');
    const file = await this.read(configPath).toPromise();
    const json = JSON.parse(fileBufferToString(file));
    const entryList = list.map((item) => `pages/${item}/${item}-entry`);
    json.pages = entryList;
    await this.write(
      configPath,
      stringToFileBuffer(JSON.stringify(json))
    ).toPromise();
  }
Example #2
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
async addSpecEntry(list: string[]) {
    const configPath = join(normalize(this.root()), 'src', 'app.json');
    const file = await this.read(configPath).toPromise();
    const json = JSON.parse(fileBufferToString(file));
    const entryList = list.map((item) => `spec/${item}/${item}-entry`);
    json.pages = entryList;
    await this.write(
      configPath,
      stringToFileBuffer(JSON.stringify(json))
    ).toPromise();
  }
Example #3
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
withBuilderTarget<O>(
    target: string,
    handler: BuilderHandlerFn<O & json.JsonObject>,
    options?: O,
    info?: Partial<BuilderInfo>
  ): this {
    this.builderTargets.set(target, {
      handler,
      options: options || {},
      info: {
        builderName: handler.name,
        description: '',
        optionSchema: true,
        ...info,
      },
    });

    return this;
  }
Example #4
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
constructor(
    private readonly builderHandler: BuilderHandlerFn<T & json.JsonObject>,
    public readonly host: MyTestProjectHost,
    builderInfo?: Partial<BuilderInfo>
  ) {
    // Generate default pseudo builder info for test purposes
    this.builderInfo = {
      builderName: builderHandler.name,
      description: '',
      optionSchema: true,
      ...builderInfo,
    };

    this.schemaRegistry.addPostTransform(
      json.schema.transforms.addUndefinedDefaults
    );
  }
Example #5
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
private builderTargets = new Map<
    string,
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    {
      handler: BuilderHandlerFn<any>;
      info: BuilderInfo;
      options: json.JsonObject;
    }
  >();
Example #6
Source File: index.ts    From angular-miniprogram with MIT License 6 votes vote down vote up
export function describeBuilder<T>(
  builderHandler: BuilderHandlerFn<T & json.JsonObject>,
  options: { name?: string; schemaPath: string },
  specDefinitions: (harness: JasmineBuilderHarness<T>) => void
): void {
  errorAndExitHook();
  jasmine.DEFAULT_TIMEOUT_INTERVAL = 500 * 1000;
  let optionSchema = optionSchemaCache.get(options.schemaPath);
  if (optionSchema === undefined) {
    optionSchema = JSON.parse(
      readFileSync(options.schemaPath, 'utf8')
    ) as json.schema.JsonSchema;
    optionSchemaCache.set(options.schemaPath, optionSchema);
  }
  const harness = new JasmineBuilderHarness<T>(builderHandler, host, {
    builderName: options.name,
    optionSchema,
  });

  describe(options.name || builderHandler.name, () => {
    beforeEach(() => host.initialize().toPromise());

    afterEach(() => host.restore().toPromise());

    specDefinitions(harness);
  });
}
Example #7
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
private schemaRegistry = new json.schema.CoreSchemaRegistry();
Example #8
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
async getProjectMetadata(
    targetOrName: Target | string
  ): Promise<json.JsonObject> {
    const project =
      typeof targetOrName === 'string' ? targetOrName : targetOrName.project;

    return this.contextHost.getMetadata(project);
  }
Example #9
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
async getTargetOptions(target: Target): Promise<json.JsonObject> {
    return this.contextHost.getOptions(
      target.project,
      target.target,
      target.configuration
    );
  }
Example #10
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
// Unused by builders in this package
  async scheduleBuilder(
    builderName: string,
    options?: json.JsonObject,
    scheduleOptions?: ScheduleOptions
  ): Promise<BuilderRun> {
    throw new Error('Not Implemented.');
  }
Example #11
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
async scheduleTarget(
    target: Target,
    overrides?: json.JsonObject,
    scheduleOptions?: ScheduleOptions
  ): Promise<BuilderRun> {
    const { info, handler } = await this.contextHost.findBuilderByTarget(
      target.project,
      target.target
    );
    const targetOptions = await this.validateOptions(
      {
        ...(await this.getTargetOptions(target)),
        ...overrides,
      },
      info.builderName
    );

    const context = new HarnessBuilderContext(
      info,
      this.workspaceRoot,
      this.contextHost,
      this.watcherFactory,
      undefined
    );
    context.target = target;
    context.logger = scheduleOptions?.logger || this.logger.createChild('');

    const progressSubject = new Subject<BuilderProgressReport>();
    const output = convertBuilderOutputToObservable(
      handler(targetOptions, context)
    );

    const run: BuilderRun = {
      id: context.id,
      info,
      progress: progressSubject.asObservable(),
      async stop() {
        for (const teardown of context.teardowns) {
          await teardown();
        }
        progressSubject.complete();
      },
      output: output.pipe(shareReplay()),
      get result() {
        return this.output.pipe(first()).toPromise();
      },
    };

    return run;
  }
Example #12
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
async validateOptions<T extends json.JsonObject = json.JsonObject>(
    options: json.JsonObject,
    builderName: string
  ): Promise<T> {
    return this.contextHost.validate(options, builderName) as unknown as T;
  }
Example #13
Source File: index.ts    From angular-miniprogram with MIT License 5 votes vote down vote up
optionSchemaCache = new Map<string, json.schema.JsonSchema>()
Example #14
Source File: index.ts    From angular-miniprogram with MIT License 4 votes vote down vote up
execute(
    options: Partial<BuilderHarnessExecutionOptions> = {}
  ): Observable<BuilderHarnessExecutionResult> {
    const {
      configuration,
      outputLogsOnException = true,
      outputLogsOnFailure = true,
      useNativeFileWatching = false,
    } = options;

    const targetOptions = {
      ...this.options.get(null),
      ...((configuration && this.options.get(configuration)) ?? {}),
    };

    if (!useNativeFileWatching) {
      if (this.watcherNotifier) {
        throw new Error('Only one harness execution at a time is supported.');
      }
      this.watcherNotifier = new WatcherNotifier();
    }

    const contextHost: ContextHost = {
      findBuilderByTarget: async (project, target) => {
        this.validateProjectName(project);
        if (target === this.targetName) {
          return {
            info: this.builderInfo,
            handler: this.builderHandler as BuilderHandlerFn<json.JsonObject>,
          };
        }

        const builderTarget = this.builderTargets.get(target);
        if (builderTarget) {
          return { info: builderTarget.info, handler: builderTarget.handler };
        }

        throw new Error('Project target does not exist.');
      },
      async getBuilderName(project, target) {
        return (await this.findBuilderByTarget(project, target)).info
          .builderName;
      },
      getMetadata: async (project) => {
        this.validateProjectName(project);

        return this.projectMetadata as json.JsonObject;
      },
      getOptions: async (project, target, configuration) => {
        this.validateProjectName(project);
        if (target === this.targetName) {
          return this.options.get(configuration ?? null) ?? {};
        } else if (configuration !== undefined) {
          // Harness builder targets currently do not support configurations
          return {};
        } else {
          return (
            (this.builderTargets.get(target)?.options as json.JsonObject) || {}
          );
        }
      },
      hasTarget: async (project, target) => {
        this.validateProjectName(project);

        return this.targetName === target || this.builderTargets.has(target);
      },
      getDefaultConfigurationName: async (_project, _target) => {
        return undefined;
      },
      validate: async (options, builderName) => {
        let schema;
        if (builderName === this.builderInfo.builderName) {
          schema = this.builderInfo.optionSchema;
        } else {
          for (const [, value] of this.builderTargets) {
            if (value.info.builderName === builderName) {
              schema = value.info.optionSchema;
              break;
            }
          }
        }

        const validator = await this.schemaRegistry
          .compile(schema ?? true)
          .toPromise();
        const { data } = await validator(options).toPromise();

        return data as json.JsonObject;
      },
    };
    const context = new HarnessBuilderContext(
      this.builderInfo,
      getSystemPath(this.host.root()),
      contextHost,
      useNativeFileWatching ? undefined : this.watcherNotifier,
      options.testContext
    );
    if (this.targetName !== undefined) {
      context.target = {
        project: this.projectName,
        target: this.targetName,
        configuration: configuration as string,
      };
    }

    const logs: logging.LogEntry[] = [];
    context.logger.subscribe((e) => logs.push(e));

    return this.schemaRegistry.compile(this.builderInfo.optionSchema).pipe(
      mergeMap((validator) => validator(targetOptions as any)),
      map((validationResult) => validationResult.data),
      mergeMap((data) =>
        convertBuilderOutputToObservable(
          this.builderHandler(data as T & json.JsonObject, context)
        )
      ),
      map((buildResult) => ({ result: buildResult, error: undefined })),
      catchError((error) => {
        if (outputLogsOnException) {
          // eslint-disable-next-line no-console
          console.error(logs.map((entry) => entry.message).join('\n'));
          // eslint-disable-next-line no-console
          console.error(error);
        }

        return of({ result: undefined, error });
      }),
      map(({ result, error }) => {
        if (
          outputLogsOnFailure &&
          result?.success === false &&
          logs.length > 0
        ) {
          // eslint-disable-next-line no-console
          console.error(logs.map((entry) => entry.message).join('\n'));
        }

        // Capture current logs and clear for next
        const currentLogs = logs.slice();
        logs.length = 0;

        return { result, error, logs: currentLogs };
      }),
      finalize(() => {
        this.watcherNotifier = undefined;

        for (const teardown of context.teardowns) {
          // eslint-disable-next-line @typescript-eslint/no-floating-promises
          teardown();
        }
      })
    );
  }