Primeiro commit do projeto Angular

This commit is contained in:
2026-03-14 20:41:55 +00:00
parent 9bebe1de72
commit 94f4f46395
22413 changed files with 3221690 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export declare class BaseException extends Error {
constructor(message?: string);
}
export declare class UnknownException extends BaseException {
constructor(message: string);
}
export declare class FileDoesNotExistException extends BaseException {
constructor(path: string);
}
export declare class FileAlreadyExistException extends BaseException {
constructor(path: string);
}
export declare class PathIsDirectoryException extends BaseException {
constructor(path: string);
}
export declare class PathIsFileException extends BaseException {
constructor(path: string);
}
+48
View File
@@ -0,0 +1,48 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PathIsFileException = exports.PathIsDirectoryException = exports.FileAlreadyExistException = exports.FileDoesNotExistException = exports.UnknownException = exports.BaseException = void 0;
class BaseException extends Error {
constructor(message = '') {
super(message);
}
}
exports.BaseException = BaseException;
class UnknownException extends BaseException {
constructor(message) {
super(message);
}
}
exports.UnknownException = UnknownException;
// Exceptions
class FileDoesNotExistException extends BaseException {
constructor(path) {
super(`Path "${path}" does not exist.`);
}
}
exports.FileDoesNotExistException = FileDoesNotExistException;
class FileAlreadyExistException extends BaseException {
constructor(path) {
super(`Path "${path}" already exist.`);
}
}
exports.FileAlreadyExistException = FileAlreadyExistException;
class PathIsDirectoryException extends BaseException {
constructor(path) {
super(`Path "${path}" is a directory.`);
}
}
exports.PathIsDirectoryException = PathIsDirectoryException;
class PathIsFileException extends BaseException {
constructor(path) {
super(`Path "${path}" is a file.`);
}
}
exports.PathIsFileException = PathIsFileException;
//# sourceMappingURL=exception.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"exception.js","sourceRoot":"","sources":["exception.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,MAAa,aAAc,SAAQ,KAAK;IACtC,YAAY,OAAO,GAAG,EAAE;QACtB,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;CACF;AAJD,sCAIC;AAED,MAAa,gBAAiB,SAAQ,aAAa;IACjD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;CACF;AAJD,4CAIC;AAED,aAAa;AACb,MAAa,yBAA0B,SAAQ,aAAa;IAC1D,YAAY,IAAY;QACtB,KAAK,CAAC,SAAS,IAAI,mBAAmB,CAAC,CAAC;IAC1C,CAAC;CACF;AAJD,8DAIC;AACD,MAAa,yBAA0B,SAAQ,aAAa;IAC1D,YAAY,IAAY;QACtB,KAAK,CAAC,SAAS,IAAI,kBAAkB,CAAC,CAAC;IACzC,CAAC;CACF;AAJD,8DAIC;AACD,MAAa,wBAAyB,SAAQ,aAAa;IACzD,YAAY,IAAY;QACtB,KAAK,CAAC,SAAS,IAAI,mBAAmB,CAAC,CAAC;IAC1C,CAAC;CACF;AAJD,4DAIC;AACD,MAAa,mBAAoB,SAAQ,aAAa;IACpD,YAAY,IAAY;QACtB,KAAK,CAAC,SAAS,IAAI,cAAc,CAAC,CAAC;IACrC,CAAC;CACF;AAJD,kDAIC"}
+15
View File
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as json from './json/index';
import * as logging from './logger/index';
import * as workspaces from './workspace';
export * from './exception';
export * from './json/index';
export * from './utils/index';
export * from './virtual-fs/index';
export { json, logging, workspaces };
+57
View File
@@ -0,0 +1,57 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.workspaces = exports.logging = exports.json = void 0;
const json = __importStar(require("./json/index"));
exports.json = json;
const logging = __importStar(require("./logger/index"));
exports.logging = logging;
const workspaces = __importStar(require("./workspace"));
exports.workspaces = workspaces;
__exportStar(require("./exception"), exports);
__exportStar(require("./json/index"), exports);
__exportStar(require("./utils/index"), exports);
__exportStar(require("./virtual-fs/index"), exports);
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,mDAAqC;AAS5B,oBAAI;AARb,wDAA0C;AAQ3B,0BAAO;AAPtB,wDAA0C;AAOlB,gCAAU;AALlC,8CAA4B;AAC5B,+CAA6B;AAC7B,gDAA8B;AAC9B,qDAAmC"}
+10
View File
@@ -0,0 +1,10 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as schema from './schema/index';
export * from './utils';
export { schema };
+50
View File
@@ -0,0 +1,50 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.schema = void 0;
const schema = __importStar(require("./schema/index"));
exports.schema = schema;
__exportStar(require("./utils"), exports);
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,uDAAyC;AAGhC,wBAAM;AADf,0CAAwB"}
+15
View File
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as transforms from './transforms';
export * from './interface';
export * from './pointer';
export * from './registry';
export * from './schema';
export * from './visitor';
export * from './utility';
export { transforms };
+55
View File
@@ -0,0 +1,55 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.transforms = void 0;
const transforms = __importStar(require("./transforms"));
exports.transforms = transforms;
__exportStar(require("./interface"), exports);
__exportStar(require("./pointer"), exports);
__exportStar(require("./registry"), exports);
__exportStar(require("./schema"), exports);
__exportStar(require("./visitor"), exports);
__exportStar(require("./utility"), exports);
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,yDAA2C;AASlC,gCAAU;AAPnB,8CAA4B;AAC5B,4CAA0B;AAC1B,6CAA2B;AAC3B,2CAAyB;AACzB,4CAA0B;AAC1B,4CAA0B"}
+84
View File
@@ -0,0 +1,84 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { ErrorObject, Format } from 'ajv';
import { Observable, ObservableInput } from 'rxjs';
import { JsonArray, JsonObject, JsonValue } from '../utils';
export type JsonPointer = string & {
__PRIVATE_DEVKIT_JSON_POINTER: void;
};
export interface SchemaValidatorResult {
data: JsonValue;
success: boolean;
errors?: SchemaValidatorError[];
}
export type SchemaValidatorError = Partial<ErrorObject>;
export interface SchemaValidatorOptions {
applyPreTransforms?: boolean;
applyPostTransforms?: boolean;
withPrompts?: boolean;
}
export interface SchemaValidator {
(data: JsonValue, options?: SchemaValidatorOptions): Promise<SchemaValidatorResult>;
}
export type SchemaFormatter = Format;
export interface SchemaFormat {
name: string;
formatter: SchemaFormatter;
}
export interface SmartDefaultProvider<T> {
(schema: JsonObject): T | Observable<T>;
}
export interface SchemaKeywordValidator {
(data: JsonValue, schema: JsonValue, parent: JsonObject | JsonArray | undefined, parentProperty: string | number | undefined, pointer: JsonPointer, rootData: JsonValue): boolean | Observable<boolean>;
}
export interface PromptDefinition {
id: string;
type: string;
message: string;
default?: string | string[] | number | boolean | null;
validator?: (value: JsonValue) => boolean | string | Promise<boolean | string>;
items?: Array<string | {
value: JsonValue;
label: string;
}>;
raw?: string | JsonObject;
multiselect?: boolean;
propertyTypes: Set<string>;
}
export type PromptProvider = (definitions: Array<PromptDefinition>) => ObservableInput<{
[id: string]: JsonValue;
}>;
export interface SchemaRegistry {
compile(schema: Object): Promise<SchemaValidator>;
/** @private */
ɵflatten(schema: JsonObject | string): Promise<JsonObject>;
addFormat(format: SchemaFormat): void;
addSmartDefaultProvider<T>(source: string, provider: SmartDefaultProvider<T>): void;
usePromptProvider(provider: PromptProvider): void;
useXDeprecatedProvider(onUsage: (message: string) => void): void;
/**
* Add a transformation step before the validation of any Json.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void;
/**
* Add a transformation step after the validation of any Json. The JSON will not be validated
* after the POST, so if transformations are not compatible with the Schema it will not result
* in an error.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void;
}
export interface JsonSchemaVisitor {
(current: JsonObject | JsonArray, pointer: JsonPointer, parentSchema?: JsonObject | JsonArray, index?: string): void;
}
export interface JsonVisitor {
(value: JsonValue, pointer: JsonPointer, schema?: JsonObject, root?: JsonObject | JsonArray): Observable<JsonValue> | JsonValue;
}
+10
View File
@@ -0,0 +1,10 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=interface.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"interface.js","sourceRoot":"","sources":["interface.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG"}
+11
View File
@@ -0,0 +1,11 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonPointer } from './interface';
export declare function buildJsonPointer(fragments: string[]): JsonPointer;
export declare function joinJsonPointer(root: JsonPointer, ...others: string[]): JsonPointer;
export declare function parseJsonPointer(pointer: JsonPointer): string[];
+39
View File
@@ -0,0 +1,39 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildJsonPointer = buildJsonPointer;
exports.joinJsonPointer = joinJsonPointer;
exports.parseJsonPointer = parseJsonPointer;
function buildJsonPointer(fragments) {
return ('/' +
fragments
.map((f) => {
return f.replace(/~/g, '~0').replace(/\//g, '~1');
})
.join('/'));
}
function joinJsonPointer(root, ...others) {
if (root == '/') {
return buildJsonPointer(others);
}
return (root + buildJsonPointer(others));
}
function parseJsonPointer(pointer) {
if (pointer === '') {
return [];
}
if (pointer.charAt(0) !== '/') {
throw new Error('Relative pointer: ' + pointer);
}
return pointer
.substring(1)
.split(/\//)
.map((str) => str.replace(/~1/g, '/').replace(/~0/g, '~'));
}
//# sourceMappingURL=pointer.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"pointer.js","sourceRoot":"","sources":["pointer.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAIH,4CAOC;AACD,0CAMC;AACD,4CAYC;AA3BD,SAAgB,gBAAgB,CAAC,SAAmB;IAClD,OAAO,CAAC,GAAG;QACT,SAAS;aACN,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;YACT,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACpD,CAAC,CAAC;aACD,IAAI,CAAC,GAAG,CAAC,CAAgB,CAAC;AACjC,CAAC;AACD,SAAgB,eAAe,CAAC,IAAiB,EAAE,GAAG,MAAgB;IACpE,IAAI,IAAI,IAAI,GAAG,EAAE,CAAC;QAChB,OAAO,gBAAgB,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;IAED,OAAO,CAAC,IAAI,GAAG,gBAAgB,CAAC,MAAM,CAAC,CAAgB,CAAC;AAC1D,CAAC;AACD,SAAgB,gBAAgB,CAAC,OAAoB;IACnD,IAAI,OAAO,KAAK,EAAE,EAAE,CAAC;QACnB,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,oBAAoB,GAAG,OAAO,CAAC,CAAC;IAClD,CAAC;IAED,OAAO,OAAO;SACX,SAAS,CAAC,CAAC,CAAC;SACZ,KAAK,CAAC,IAAI,CAAC;SACX,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC;AAC/D,CAAC"}
+79
View File
@@ -0,0 +1,79 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { ValidateFunction } from 'ajv';
import { Observable } from 'rxjs';
import { BaseException } from '../../exception';
import { JsonObject } from '../utils';
import { JsonVisitor, PromptProvider, SchemaFormat, SchemaRegistry, SchemaValidator, SchemaValidatorError, SmartDefaultProvider } from './interface';
import { JsonSchema } from './schema';
export type UriHandler = (uri: string) => Observable<JsonObject> | Promise<JsonObject> | null | undefined;
export declare class SchemaValidationException extends BaseException {
readonly errors: SchemaValidatorError[];
constructor(errors?: SchemaValidatorError[], baseMessage?: string);
static createMessages(errors?: SchemaValidatorError[]): string[];
}
export declare class CoreSchemaRegistry implements SchemaRegistry {
private _ajv;
private _uriCache;
private _uriHandlers;
private _pre;
private _post;
private _currentCompilationSchemaInfo?;
private _smartDefaultKeyword;
private _promptProvider?;
private _sourceMap;
constructor(formats?: SchemaFormat[]);
private _fetch;
/**
* Add a transformation step before the validation of any Json.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPreTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void;
/**
* Add a transformation step after the validation of any Json. The JSON will not be validated
* after the POST, so if transformations are not compatible with the Schema it will not result
* in an error.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPostTransform(visitor: JsonVisitor, deps?: JsonVisitor[]): void;
protected _resolver(ref: string, validate?: ValidateFunction): {
context?: ValidateFunction;
schema?: JsonObject;
};
/**
* Flatten the Schema, resolving and replacing all the refs. Makes it into a synchronous schema
* that is also easier to traverse. Does not cache the result.
*
* Producing a flatten schema document does not in all cases produce a schema with identical behavior to the original.
* See: https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.appendix.B.2
*
* @param schema The schema or URI to flatten.
* @returns An Observable of the flattened schema object.
* @private since 11.2 without replacement.
*/
ɵflatten(schema: JsonObject): Promise<JsonObject>;
/**
* Compile and return a validation function for the Schema.
*
* @param schema The schema to validate. If a string, will fetch the schema before compiling it
* (using schema as a URI).
*/
compile(schema: JsonSchema): Promise<SchemaValidator>;
private _compile;
addFormat(format: SchemaFormat): void;
addSmartDefaultProvider<T>(source: string, provider: SmartDefaultProvider<T>): void;
registerUriHandler(handler: UriHandler): void;
usePromptProvider(provider: PromptProvider): void;
private _applyPrompts;
private static _set;
private _applySmartDefaults;
useXDeprecatedProvider(onUsage: (message: string) => void): void;
private normalizeDataPathArr;
}
+565
View File
@@ -0,0 +1,565 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CoreSchemaRegistry = exports.SchemaValidationException = void 0;
const ajv_1 = __importDefault(require("ajv"));
const ajv_formats_1 = __importDefault(require("ajv-formats"));
const http = __importStar(require("node:http"));
const https = __importStar(require("node:https"));
const Url = __importStar(require("node:url"));
const rxjs_1 = require("rxjs");
const exception_1 = require("../../exception");
const utils_1 = require("../../utils");
const utils_2 = require("../utils");
const utility_1 = require("./utility");
const visitor_1 = require("./visitor");
class SchemaValidationException extends exception_1.BaseException {
errors;
constructor(errors, baseMessage = 'Schema validation failed with the following errors:') {
if (!errors || errors.length === 0) {
super('Schema validation failed.');
this.errors = [];
return;
}
const messages = SchemaValidationException.createMessages(errors);
super(`${baseMessage}\n ${messages.join('\n ')}`);
this.errors = errors;
}
static createMessages(errors) {
if (!errors || errors.length === 0) {
return [];
}
const messages = errors.map((err) => {
let message = `Data path ${JSON.stringify(err.instancePath)} ${err.message}`;
if (err.params) {
switch (err.keyword) {
case 'additionalProperties':
message += `(${err.params.additionalProperty})`;
break;
case 'enum':
message += `. Allowed values are: ${err.params.allowedValues
?.map((v) => `"${v}"`)
.join(', ')}`;
break;
}
}
return message + '.';
});
return messages;
}
}
exports.SchemaValidationException = SchemaValidationException;
class CoreSchemaRegistry {
_ajv;
_uriCache = new Map();
_uriHandlers = new Set();
_pre = new utils_1.PartiallyOrderedSet();
_post = new utils_1.PartiallyOrderedSet();
_currentCompilationSchemaInfo;
_smartDefaultKeyword = false;
_promptProvider;
_sourceMap = new Map();
constructor(formats = []) {
this._ajv = new ajv_1.default({
strict: false,
loadSchema: (uri) => this._fetch(uri),
passContext: true,
});
(0, ajv_formats_1.default)(this._ajv);
for (const format of formats) {
this.addFormat(format);
}
}
async _fetch(uri) {
const maybeSchema = this._uriCache.get(uri);
if (maybeSchema) {
return maybeSchema;
}
// Try all handlers, one after the other.
for (const handler of this._uriHandlers) {
let handlerResult = handler(uri);
if (handlerResult === null || handlerResult === undefined) {
continue;
}
if ((0, rxjs_1.isObservable)(handlerResult)) {
handlerResult = (0, rxjs_1.lastValueFrom)(handlerResult);
}
const value = await handlerResult;
this._uriCache.set(uri, value);
return value;
}
// If none are found, handle using http client.
return new Promise((resolve, reject) => {
const url = new Url.URL(uri);
const client = url.protocol === 'https:' ? https : http;
client.get(url, (res) => {
if (!res.statusCode || res.statusCode >= 300) {
// Consume the rest of the data to free memory.
res.resume();
reject(new Error(`Request failed. Status Code: ${res.statusCode}`));
}
else {
res.setEncoding('utf8');
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const json = JSON.parse(data);
this._uriCache.set(uri, json);
resolve(json);
}
catch (err) {
reject(err);
}
});
}
});
});
}
/**
* Add a transformation step before the validation of any Json.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPreTransform(visitor, deps) {
this._pre.add(visitor, deps);
}
/**
* Add a transformation step after the validation of any Json. The JSON will not be validated
* after the POST, so if transformations are not compatible with the Schema it will not result
* in an error.
* @param {JsonVisitor} visitor The visitor to transform every value.
* @param {JsonVisitor[]} deps A list of other visitors to run before.
*/
addPostTransform(visitor, deps) {
this._post.add(visitor, deps);
}
_resolver(ref, validate) {
if (!validate || !ref) {
return {};
}
const schema = validate.schemaEnv.root.schema;
const id = typeof schema === 'object' ? schema.$id : null;
let fullReference = ref;
if (typeof id === 'string') {
fullReference = Url.resolve(id, ref);
if (ref.startsWith('#')) {
fullReference = id + fullReference;
}
}
const resolvedSchema = this._ajv.getSchema(fullReference);
return {
context: resolvedSchema?.schemaEnv.validate,
schema: resolvedSchema?.schema,
};
}
/**
* Flatten the Schema, resolving and replacing all the refs. Makes it into a synchronous schema
* that is also easier to traverse. Does not cache the result.
*
* Producing a flatten schema document does not in all cases produce a schema with identical behavior to the original.
* See: https://json-schema.org/draft/2019-09/json-schema-core.html#rfc.appendix.B.2
*
* @param schema The schema or URI to flatten.
* @returns An Observable of the flattened schema object.
* @private since 11.2 without replacement.
*/
async ɵflatten(schema) {
this._ajv.removeSchema(schema);
this._currentCompilationSchemaInfo = undefined;
const validate = await this._ajv.compileAsync(schema);
// eslint-disable-next-line @typescript-eslint/no-this-alias
const self = this;
function visitor(current, pointer, parentSchema, index) {
if (current &&
parentSchema &&
index &&
(0, utils_2.isJsonObject)(current) &&
Object.prototype.hasOwnProperty.call(current, '$ref') &&
typeof current['$ref'] == 'string') {
const resolved = self._resolver(current['$ref'], validate);
if (resolved.schema) {
parentSchema[index] = resolved.schema;
}
}
}
const schemaCopy = (0, utils_1.deepCopy)(validate.schema);
(0, visitor_1.visitJsonSchema)(schemaCopy, visitor);
return schemaCopy;
}
/**
* Compile and return a validation function for the Schema.
*
* @param schema The schema to validate. If a string, will fetch the schema before compiling it
* (using schema as a URI).
*/
async compile(schema) {
const validate = await this._compile(schema);
return (value, options) => validate(value, options);
}
async _compile(schema) {
if (typeof schema === 'boolean') {
return async (data) => ({ success: schema, data });
}
const schemaInfo = {
smartDefaultRecord: new Map(),
promptDefinitions: [],
};
this._ajv.removeSchema(schema);
let validator;
try {
this._currentCompilationSchemaInfo = schemaInfo;
validator = this._ajv.compile(schema);
}
catch (e) {
// This should eventually be refactored so that we we handle race condition where the same schema is validated at the same time.
if (!(e instanceof ajv_1.default.MissingRefError)) {
throw e;
}
validator = await this._ajv.compileAsync(schema);
}
finally {
this._currentCompilationSchemaInfo = undefined;
}
return async (data, options) => {
const validationOptions = {
withPrompts: true,
applyPostTransforms: true,
applyPreTransforms: true,
...options,
};
const validationContext = {
promptFieldsWithValue: new Set(),
};
// Apply pre-validation transforms
if (validationOptions.applyPreTransforms) {
for (const visitor of this._pre.values()) {
data = await (0, rxjs_1.lastValueFrom)((0, visitor_1.visitJson)(data, visitor, schema, this._resolver.bind(this), validator));
}
}
// Apply smart defaults
await this._applySmartDefaults(data, schemaInfo.smartDefaultRecord);
// Apply prompts
if (validationOptions.withPrompts) {
const visitor = (value, pointer) => {
if (value !== undefined) {
validationContext.promptFieldsWithValue.add(pointer);
}
return value;
};
if (typeof schema === 'object') {
await (0, rxjs_1.lastValueFrom)((0, visitor_1.visitJson)(data, visitor, schema, this._resolver.bind(this), validator));
}
const definitions = schemaInfo.promptDefinitions.filter((def) => !validationContext.promptFieldsWithValue.has(def.id));
if (definitions.length > 0) {
await this._applyPrompts(data, definitions);
}
}
// Validate using ajv
try {
// eslint-disable-next-line @typescript-eslint/await-thenable
const success = await validator.call(validationContext, data);
if (!success) {
return { data, success, errors: validator.errors ?? [] };
}
}
catch (error) {
if (error instanceof ajv_1.default.ValidationError) {
return { data, success: false, errors: error.errors };
}
throw error;
}
// Apply post-validation transforms
if (validationOptions.applyPostTransforms) {
for (const visitor of this._post.values()) {
data = await (0, rxjs_1.lastValueFrom)((0, visitor_1.visitJson)(data, visitor, schema, this._resolver.bind(this), validator));
}
}
return { data, success: true };
};
}
addFormat(format) {
this._ajv.addFormat(format.name, format.formatter);
}
addSmartDefaultProvider(source, provider) {
if (this._sourceMap.has(source)) {
throw new Error(source);
}
this._sourceMap.set(source, provider);
if (!this._smartDefaultKeyword) {
this._smartDefaultKeyword = true;
this._ajv.addKeyword({
keyword: '$default',
errors: false,
valid: true,
compile: (schema, _parentSchema, it) => {
const compilationSchemInfo = this._currentCompilationSchemaInfo;
if (compilationSchemInfo === undefined) {
return () => true;
}
// We cheat, heavily.
const pathArray = this.normalizeDataPathArr(it);
compilationSchemInfo.smartDefaultRecord.set(JSON.stringify(pathArray), schema);
return () => true;
},
metaSchema: {
type: 'object',
properties: {
'$source': { type: 'string' },
},
additionalProperties: true,
required: ['$source'],
},
});
}
}
registerUriHandler(handler) {
this._uriHandlers.add(handler);
}
usePromptProvider(provider) {
const isSetup = !!this._promptProvider;
this._promptProvider = provider;
if (isSetup) {
return;
}
this._ajv.addKeyword({
keyword: 'x-prompt',
errors: false,
valid: true,
compile: (schema, parentSchema, it) => {
const compilationSchemInfo = this._currentCompilationSchemaInfo;
if (!compilationSchemInfo) {
return () => true;
}
const path = '/' + this.normalizeDataPathArr(it).join('/');
let type;
let items;
let message;
if (typeof schema == 'string') {
message = schema;
}
else {
message = schema.message;
type = schema.type;
items = schema.items;
}
const propertyTypes = (0, utility_1.getTypesOfSchema)(parentSchema);
if (!type) {
if (propertyTypes.size === 1 && propertyTypes.has('boolean')) {
type = 'confirmation';
}
else if (Array.isArray(parentSchema.enum)) {
type = 'list';
}
else if (propertyTypes.size === 1 &&
propertyTypes.has('array') &&
parentSchema.items &&
Array.isArray(parentSchema.items.enum)) {
type = 'list';
}
else {
type = 'input';
}
}
let multiselect;
if (type === 'list') {
multiselect =
schema.multiselect === undefined
? propertyTypes.size === 1 && propertyTypes.has('array')
: schema.multiselect;
const enumValues = multiselect
? parentSchema.items &&
parentSchema.items.enum
: parentSchema.enum;
if (!items && Array.isArray(enumValues)) {
items = [];
for (const value of enumValues) {
if (typeof value == 'string') {
items.push(value);
}
else if (typeof value == 'object') {
// Invalid
}
else {
items.push({ label: value.toString(), value });
}
}
}
}
const definition = {
id: path,
type,
message,
raw: schema,
items,
multiselect,
propertyTypes,
default: typeof parentSchema.default == 'object' &&
parentSchema.default !== null &&
!Array.isArray(parentSchema.default)
? undefined
: parentSchema.default,
async validator(data) {
try {
const result = await it.self.validate(parentSchema, data);
// If the schema is sync then false will be returned on validation failure
if (result) {
return result;
}
else if (it.self.errors?.length) {
// Validation errors will be present on the Ajv instance when sync
return it.self.errors[0].message;
}
}
catch (e) {
const validationError = e;
// If the schema is async then an error will be thrown on validation failure
if (Array.isArray(validationError.errors) && validationError.errors.length) {
return validationError.errors[0].message;
}
}
return false;
},
};
compilationSchemInfo.promptDefinitions.push(definition);
return function () {
// If 'this' is undefined in the call, then it defaults to the global
// 'this'.
if (this && this.promptFieldsWithValue) {
this.promptFieldsWithValue.add(path);
}
return true;
};
},
metaSchema: {
oneOf: [
{ type: 'string' },
{
type: 'object',
properties: {
'type': { type: 'string' },
'message': { type: 'string' },
},
additionalProperties: true,
required: ['message'],
},
],
},
});
}
async _applyPrompts(data, prompts) {
const provider = this._promptProvider;
if (!provider) {
return;
}
const answers = await (0, rxjs_1.lastValueFrom)((0, rxjs_1.from)(provider(prompts)));
for (const path in answers) {
const pathFragments = path.split('/').slice(1);
CoreSchemaRegistry._set(data, pathFragments, answers[path], null, undefined, true);
}
}
static _set(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data, fragments, value,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
parent = null, parentProperty, force) {
for (let index = 0; index < fragments.length; index++) {
const fragment = fragments[index];
if (/^i\d+$/.test(fragment)) {
if (!Array.isArray(data)) {
return;
}
for (let dataIndex = 0; dataIndex < data.length; dataIndex++) {
CoreSchemaRegistry._set(data[dataIndex], fragments.slice(index + 1), value, data, `${dataIndex}`);
}
return;
}
if (!data && parent !== null && parentProperty) {
data = parent[parentProperty] = {};
}
parent = data;
parentProperty = fragment;
data = data[fragment];
}
if (parent && parentProperty && (force || parent[parentProperty] === undefined)) {
parent[parentProperty] = value;
}
}
async _applySmartDefaults(data, smartDefaults) {
for (const [pointer, schema] of smartDefaults.entries()) {
const fragments = JSON.parse(pointer);
const source = this._sourceMap.get(schema.$source);
if (!source) {
continue;
}
let value = source(schema);
if ((0, rxjs_1.isObservable)(value)) {
value = (await (0, rxjs_1.lastValueFrom)(value));
}
CoreSchemaRegistry._set(data, fragments, value);
}
}
useXDeprecatedProvider(onUsage) {
this._ajv.addKeyword({
keyword: 'x-deprecated',
validate: (schema, _data, _parentSchema, dataCxt) => {
if (schema) {
onUsage(`Option "${dataCxt?.parentDataProperty}" is deprecated${typeof schema == 'string' ? ': ' + schema : '.'}`);
}
return true;
},
errors: false,
});
}
normalizeDataPathArr(it) {
return it.dataPathArr
.slice(1, it.dataLevel + 1)
.map((p) => (typeof p === 'number' ? p : p.str.replace(/"/g, '')));
}
}
exports.CoreSchemaRegistry = CoreSchemaRegistry;
//# sourceMappingURL=registry.js.map
File diff suppressed because one or more lines are too long
+22
View File
@@ -0,0 +1,22 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonObject } from '../utils';
/**
* A specialized interface for JsonSchema (to come). JsonSchemas are also JsonObject.
*
* @public
*/
export type JsonSchema = JsonObject | boolean;
export declare function isJsonSchema(value: unknown): value is JsonSchema;
/**
* Return a schema that is the merge of all subschemas, ie. it should validate all the schemas
* that were passed in. It is possible to make an invalid schema this way, e.g. by using
* `mergeSchemas({ type: 'number' }, { type: 'string' })`, which will never validate.
* @param schemas All schemas to be merged.
*/
export declare function mergeSchemas(...schemas: (JsonSchema | undefined)[]): JsonSchema;
+52
View File
@@ -0,0 +1,52 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isJsonSchema = isJsonSchema;
exports.mergeSchemas = mergeSchemas;
const utils_1 = require("../utils");
function isJsonSchema(value) {
return (0, utils_1.isJsonObject)(value) || value === false || value === true;
}
/**
* Return a schema that is the merge of all subschemas, ie. it should validate all the schemas
* that were passed in. It is possible to make an invalid schema this way, e.g. by using
* `mergeSchemas({ type: 'number' }, { type: 'string' })`, which will never validate.
* @param schemas All schemas to be merged.
*/
function mergeSchemas(...schemas) {
return schemas.reduce((prev, curr) => {
if (curr === undefined) {
return prev;
}
if (prev === false || curr === false) {
return false;
}
else if (prev === true) {
return curr;
}
else if (curr === true) {
return prev;
}
else if (Array.isArray(prev.allOf)) {
if (Array.isArray(curr.allOf)) {
return { ...prev, allOf: [...prev.allOf, ...curr.allOf] };
}
else {
return { ...prev, allOf: [...prev.allOf, curr] };
}
}
else if (Array.isArray(curr.allOf)) {
return { ...prev, allOf: [prev, ...curr.allOf] };
}
else {
return { ...prev, allOf: [prev, curr] };
}
}, true);
}
//# sourceMappingURL=schema.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"schema.js","sourceRoot":"","sources":["schema.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAWH,oCAEC;AAQD,oCAwBC;AA3CD,oCAA+D;AAS/D,SAAgB,YAAY,CAAC,KAAc;IACzC,OAAO,IAAA,oBAAY,EAAC,KAAkB,CAAC,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,KAAK,IAAI,CAAC;AAC/E,CAAC;AAED;;;;;GAKG;AACH,SAAgB,YAAY,CAAC,GAAG,OAAmC;IACjE,OAAO,OAAO,CAAC,MAAM,CAAa,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE;QAC/C,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,IAAI,CAAC;QACd,CAAC;QAED,IAAI,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,EAAE,CAAC;YACrC,OAAO,KAAK,CAAC;QACf,CAAC;aAAM,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YACzB,OAAO,IAAI,CAAC;QACd,CAAC;aAAM,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YACzB,OAAO,IAAI,CAAC;QACd,CAAC;aAAM,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACrC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;gBAC9B,OAAO,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5D,CAAC;iBAAM,CAAC;gBACN,OAAO,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC;YACnD,CAAC;QACH,CAAC;aAAM,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YACrC,OAAO,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QACnD,CAAC;aAAM,CAAC;YACN,OAAO,EAAE,GAAG,IAAI,EAAE,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC;QAC1C,CAAC;IACH,CAAC,EAAE,IAAI,CAAC,CAAC;AACX,CAAC"}
+12
View File
@@ -0,0 +1,12 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonValue } from '../utils';
import { JsonPointer } from './interface';
import { JsonSchema } from './schema';
export declare function addUndefinedObjectDefaults(value: JsonValue, _pointer: JsonPointer, schema?: JsonSchema): JsonValue;
export declare function addUndefinedDefaults(value: JsonValue, _pointer: JsonPointer, schema?: JsonSchema): JsonValue;
+101
View File
@@ -0,0 +1,101 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.addUndefinedObjectDefaults = addUndefinedObjectDefaults;
exports.addUndefinedDefaults = addUndefinedDefaults;
const utils_1 = require("../utils");
const utility_1 = require("./utility");
function addUndefinedObjectDefaults(value, _pointer, schema) {
return transformUndefined(value, _pointer, schema, true);
}
function addUndefinedDefaults(value, _pointer, schema) {
return transformUndefined(value, _pointer, schema, false);
}
function transformUndefined(value, _pointer, schema, onlyObjects) {
if (typeof schema === 'boolean' || schema === undefined) {
return value;
}
value ??= schema.default;
const types = (0, utility_1.getTypesOfSchema)(schema);
if (types.size === 0) {
return value;
}
let type;
if (types.size === 1) {
// only one potential type
type = Array.from(types)[0];
}
else if (types.size === 2 && types.has('array') && types.has('object')) {
// need to create one of them and array is simpler
type = 'array';
}
else if (schema.properties && types.has('object')) {
// assume object
type = 'object';
}
else if (schema.items && types.has('array')) {
// assume array
type = 'array';
}
else {
// anything else needs to be checked by the consumer anyway
return value;
}
if (!onlyObjects && type === 'array') {
return value == undefined ? [] : value;
}
if (type === 'object') {
let newValue;
if (value == undefined) {
newValue = {};
}
else if ((0, utils_1.isJsonObject)(value)) {
newValue = value;
}
else {
return value;
}
if (!(0, utils_1.isJsonObject)(schema.properties)) {
return newValue;
}
for (const [propName, schemaObject] of Object.entries(schema.properties)) {
if (propName === '$schema' || !(0, utils_1.isJsonObject)(schemaObject)) {
continue;
}
const value = newValue[propName];
if (value === undefined) {
newValue[propName] = schemaObject.default;
}
else if ((0, utils_1.isJsonObject)(value)) {
// Basic support for oneOf and anyOf.
const propertySchemas = schemaObject.oneOf || schemaObject.anyOf;
const allProperties = Object.keys(value);
// Locate a schema which declares all the properties that the object contains.
const adjustedSchema = (0, utils_1.isJsonArray)(propertySchemas) &&
propertySchemas.find((s) => {
if (!(0, utils_1.isJsonObject)(s)) {
return false;
}
const schemaType = (0, utility_1.getTypesOfSchema)(s);
if (schemaType.size === 1 && schemaType.has('object') && (0, utils_1.isJsonObject)(s.properties)) {
const properties = Object.keys(s.properties);
return allProperties.every((key) => properties.includes(key));
}
return false;
});
if (adjustedSchema && (0, utils_1.isJsonObject)(adjustedSchema)) {
newValue[propName] = transformUndefined(value, _pointer, adjustedSchema, onlyObjects);
}
}
}
return newValue;
}
return value;
}
//# sourceMappingURL=transforms.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"transforms.js","sourceRoot":"","sources":["transforms.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAOH,gEAMC;AAED,oDAMC;AAnBD,oCAA4E;AAG5E,uCAA6C;AAE7C,SAAgB,0BAA0B,CACxC,KAAgB,EAChB,QAAqB,EACrB,MAAmB;IAEnB,OAAO,kBAAkB,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;AAC3D,CAAC;AAED,SAAgB,oBAAoB,CAClC,KAAgB,EAChB,QAAqB,EACrB,MAAmB;IAEnB,OAAO,kBAAkB,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,kBAAkB,CACzB,KAAgB,EAChB,QAAqB,EACrB,MAAmB,EACnB,WAAqB;IAErB,IAAI,OAAO,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACxD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK,KAAK,MAAM,CAAC,OAAO,CAAC;IAEzB,MAAM,KAAK,GAAG,IAAA,0BAAgB,EAAC,MAAM,CAAC,CAAC;IACvC,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,IAAI,CAAC;IACT,IAAI,KAAK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AAQ,CAAC,GAAG,CAAC,CAAC,CAAC;wBAChE,CAAC;wBAED,OAAO,KAAK,CAAC;oBACf,CAAC,CAAC,CAAC;gBAEL,IAAI,cAAc,IAAI,IAAA,oBAAY,EAAC,cAAc,CAAC,EAAE,CAAC;oBACnD,QAAQ,CAAC,QAAQ,CAAC,GAAG,kBAAkB,CAAC,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,WAAW,CAAC,CAAC;gBACxF,CAAC;YACH,CAAC;QACH,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
+9
View File
@@ -0,0 +1,9 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonSchema } from './schema';
export declare function getTypesOfSchema(schema: JsonSchema): Set<string>;
+88
View File
@@ -0,0 +1,88 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.getTypesOfSchema = getTypesOfSchema;
const utils_1 = require("../utils");
const allTypes = ['string', 'integer', 'number', 'object', 'array', 'boolean', 'null'];
function getTypesOfSchema(schema) {
if (!schema) {
return new Set();
}
if (schema === true) {
return new Set(allTypes);
}
let potentials;
if (typeof schema.type === 'string') {
potentials = new Set([schema.type]);
}
else if (Array.isArray(schema.type)) {
potentials = new Set(schema.type);
}
else if ((0, utils_1.isJsonArray)(schema.enum)) {
potentials = new Set();
// Gather the type of each enum values, and use that as a starter for potential types.
for (const v of schema.enum) {
switch (typeof v) {
case 'string':
case 'number':
case 'boolean':
potentials.add(typeof v);
break;
case 'object':
if (Array.isArray(v)) {
potentials.add('array');
}
else if (v === null) {
potentials.add('null');
}
else {
potentials.add('object');
}
break;
}
}
}
else {
potentials = new Set(allTypes);
}
if ((0, utils_1.isJsonObject)(schema.not)) {
const notTypes = getTypesOfSchema(schema.not);
potentials = new Set([...potentials].filter((p) => !notTypes.has(p)));
}
if (Array.isArray(schema.allOf)) {
for (const sub of schema.allOf) {
const types = getTypesOfSchema(sub);
potentials = new Set([...types].filter((t) => potentials.has(t)));
}
}
if (Array.isArray(schema.oneOf)) {
let options = new Set();
for (const sub of schema.oneOf) {
const types = getTypesOfSchema(sub);
options = new Set([...options, ...types]);
}
potentials = new Set([...options].filter((o) => potentials.has(o)));
}
if (Array.isArray(schema.anyOf)) {
let options = new Set();
for (const sub of schema.anyOf) {
const types = getTypesOfSchema(sub);
options = new Set([...options, ...types]);
}
potentials = new Set([...options].filter((o) => potentials.has(o)));
}
if (schema.properties) {
potentials.add('object');
}
else if (schema.items) {
potentials.add('array');
}
return potentials;
}
//# sourceMappingURL=utility.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utility.js","sourceRoot":"","sources":["utility.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAOH,4CA6EC;AAlFD,oCAAiE;AAGjE,MAAM,QAAQ,GAAG,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;AAEvF,SAAgB,gBAAgB,CAAC,MAAkB;IACjD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,IAAI,GAAG,EAAE,CAAC;IACnB,CAAC;IACD,IAAI,MAAM,KAAK,IAAI,EAAE,CAAC;QACpB,OAAO,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC3B,CAAC;IAED,IAAI,UAAuB,CAAC;IAC5B,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QACpC,UAAU,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;IACtC,CAAC;SAAM,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,EAA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AG,IAAI,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACtE,CAAC;IAED,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;QACtB,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC3B,CAAC;SAAM,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;QACxB,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAC1B,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC"}
+34
View File
@@ -0,0 +1,34 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Observable } from 'rxjs';
import { JsonObject, JsonValue } from '../utils';
import { JsonSchemaVisitor, JsonVisitor } from './interface';
import { JsonSchema } from './schema';
export interface ReferenceResolver<ContextT> {
(ref: string, context?: ContextT): {
context?: ContextT;
schema?: JsonObject;
};
}
/**
* Visit all the properties in a JSON object, allowing to transform them. It supports calling
* properties synchronously or asynchronously (through Observables).
* The original object can be mutated or replaced entirely. In case where it's replaced, the new
* value is returned. When it's mutated though the original object will be changed.
*
* Please note it is possible to have an infinite loop here (which will result in a stack overflow)
* if you return 2 objects that references each others (or the same object all the time).
*
* @param {JsonValue} json The Json value to visit.
* @param {JsonVisitor} visitor A function that will be called on every items.
* @param {JsonObject} schema A JSON schema to pass through to the visitor (where possible).
* @param refResolver a function to resolve references in the schema.
* @returns {Observable< | undefined>} The observable of the new root, if the root changed.
*/
export declare function visitJson<ContextT>(json: JsonValue, visitor: JsonVisitor, schema?: JsonSchema, refResolver?: ReferenceResolver<ContextT>, context?: ContextT): Observable<JsonValue>;
export declare function visitJsonSchema(schema: JsonSchema, visitor: JsonSchemaVisitor): void;
+147
View File
@@ -0,0 +1,147 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.visitJson = visitJson;
exports.visitJsonSchema = visitJsonSchema;
const rxjs_1 = require("rxjs");
const pointer_1 = require("./pointer");
function _getObjectSubSchema(schema, key) {
if (typeof schema !== 'object' || schema === null) {
return undefined;
}
// Is it an object schema?
if (typeof schema.properties == 'object' || schema.type == 'object') {
if (typeof schema.properties == 'object' &&
typeof schema.properties[key] == 'object') {
return schema.properties[key];
}
if (typeof schema.additionalProperties == 'object') {
return schema.additionalProperties;
}
return undefined;
}
// Is it an array schema?
if (typeof schema.items == 'object' || schema.type == 'array') {
return typeof schema.items == 'object' ? schema.items : undefined;
}
return undefined;
}
function _visitJsonRecursive(json, visitor, ptr, schema, refResolver, context, root) {
if (schema === true || schema === false) {
// There's no schema definition, so just visit the JSON recursively.
schema = undefined;
}
// eslint-disable-next-line no-prototype-builtins
if (schema && schema.hasOwnProperty('$ref') && typeof schema['$ref'] == 'string') {
if (refResolver) {
const resolved = refResolver(schema['$ref'], context);
schema = resolved.schema;
context = resolved.context;
}
}
const value = visitor(json, ptr, schema, root);
return ((0, rxjs_1.isObservable)(value) ? value : (0, rxjs_1.of)(value)).pipe((0, rxjs_1.concatMap)((value) => {
if (Array.isArray(value)) {
return (0, rxjs_1.concat)((0, rxjs_1.from)(value).pipe((0, rxjs_1.mergeMap)((item, i) => {
return _visitJsonRecursive(item, visitor, (0, pointer_1.joinJsonPointer)(ptr, '' + i), _getObjectSubSchema(schema, '' + i), refResolver, context, root || value).pipe((0, rxjs_1.tap)((x) => (value[i] = x)));
}), (0, rxjs_1.ignoreElements)()), (0, rxjs_1.of)(value));
}
else if (typeof value == 'object' && value !== null) {
return (0, rxjs_1.concat)((0, rxjs_1.from)(Object.getOwnPropertyNames(value)).pipe((0, rxjs_1.mergeMap)((key) => {
return _visitJsonRecursive(value[key], visitor, (0, pointer_1.joinJsonPointer)(ptr, key), _getObjectSubSchema(schema, key), refResolver, context, root || value).pipe((0, rxjs_1.tap)((x) => {
const descriptor = Object.getOwnPropertyDescriptor(value, key);
if (descriptor && descriptor.writable && value[key] !== x) {
value[key] = x;
}
}));
}), (0, rxjs_1.ignoreElements)()), (0, rxjs_1.of)(value));
}
else {
return (0, rxjs_1.of)(value);
}
}));
}
/**
* Visit all the properties in a JSON object, allowing to transform them. It supports calling
* properties synchronously or asynchronously (through Observables).
* The original object can be mutated or replaced entirely. In case where it's replaced, the new
* value is returned. When it's mutated though the original object will be changed.
*
* Please note it is possible to have an infinite loop here (which will result in a stack overflow)
* if you return 2 objects that references each others (or the same object all the time).
*
* @param {JsonValue} json The Json value to visit.
* @param {JsonVisitor} visitor A function that will be called on every items.
* @param {JsonObject} schema A JSON schema to pass through to the visitor (where possible).
* @param refResolver a function to resolve references in the schema.
* @returns {Observable< | undefined>} The observable of the new root, if the root changed.
*/
function visitJson(json, visitor, schema, refResolver, context) {
return _visitJsonRecursive(json, visitor, (0, pointer_1.buildJsonPointer)([]), schema, refResolver, context);
}
function visitJsonSchema(schema, visitor) {
if (schema === false || schema === true) {
// Nothing to visit.
return;
}
const keywords = {
additionalItems: true,
items: true,
contains: true,
additionalProperties: true,
propertyNames: true,
not: true,
};
const arrayKeywords = {
items: true,
allOf: true,
anyOf: true,
oneOf: true,
};
const propsKeywords = {
definitions: true,
properties: true,
patternProperties: true,
additionalProperties: true,
dependencies: true,
items: true,
};
function _traverse(schema, jsonPtr, rootSchema, parentSchema, keyIndex) {
if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
visitor(schema, jsonPtr, parentSchema, keyIndex);
for (const key of Object.keys(schema)) {
const sch = schema[key];
if (key in propsKeywords) {
if (sch && typeof sch == 'object') {
for (const prop of Object.keys(sch)) {
_traverse(sch[prop], (0, pointer_1.joinJsonPointer)(jsonPtr, key, prop), rootSchema, schema, prop);
}
}
}
else if (key in keywords) {
_traverse(sch, (0, pointer_1.joinJsonPointer)(jsonPtr, key), rootSchema, schema, key);
}
else if (key in arrayKeywords) {
if (Array.isArray(sch)) {
for (let i = 0; i < sch.length; i++) {
_traverse(sch[i], (0, pointer_1.joinJsonPointer)(jsonPtr, key, '' + i), rootSchema, sch, '' + i);
}
}
}
else if (Array.isArray(sch)) {
for (let i = 0; i < sch.length; i++) {
_traverse(sch[i], (0, pointer_1.joinJsonPointer)(jsonPtr, key, '' + i), rootSchema, sch, '' + i);
}
}
}
}
}
_traverse(schema, (0, pointer_1.buildJsonPointer)([]), schema);
}
//# sourceMappingURL=visitor.js.map
File diff suppressed because one or more lines are too long
+15
View File
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export interface JsonArray extends Array<JsonValue> {
}
export interface JsonObject {
[prop: string]: JsonValue;
}
export type JsonValue = boolean | string | number | JsonArray | JsonObject | null;
export declare function isJsonObject(value: JsonValue): value is JsonObject;
export declare function isJsonArray(value: JsonValue): value is JsonArray;
+18
View File
@@ -0,0 +1,18 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isJsonObject = isJsonObject;
exports.isJsonArray = isJsonArray;
function isJsonObject(value) {
return value != null && typeof value === 'object' && !Array.isArray(value);
}
function isJsonArray(value) {
return Array.isArray(value);
}
//# sourceMappingURL=utils.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["utils.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAWH,oCAEC;AAED,kCAEC;AAND,SAAgB,YAAY,CAAC,KAAgB;IAC3C,OAAO,KAAK,IAAI,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC7E,CAAC;AAED,SAAgB,WAAW,CAAC,KAAgB;IAC1C,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC"}
+11
View File
@@ -0,0 +1,11 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Logger } from './logger';
export declare class IndentLogger extends Logger {
constructor(name: string, parent?: Logger | null, indentation?: string);
}
+41
View File
@@ -0,0 +1,41 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.IndentLogger = void 0;
const rxjs_1 = require("rxjs");
const logger_1 = require("./logger");
/**
* Keep an map of indentation => array of indentations based on the level.
* This is to optimize calculating the prefix based on the indentation itself. Since most logs
* come from similar levels, and with similar indentation strings, this will be shared by all
* loggers. Also, string concatenation is expensive so performing concats for every log entries
* is expensive; this alleviates it.
*/
const indentationMap = {};
class IndentLogger extends logger_1.Logger {
constructor(name, parent = null, indentation = ' ') {
super(name, parent);
indentationMap[indentation] = indentationMap[indentation] || [''];
const indentMap = indentationMap[indentation];
this._observable = this._observable.pipe((0, rxjs_1.map)((entry) => {
const l = entry.path.filter((x) => !!x).length;
if (l >= indentMap.length) {
let current = indentMap[indentMap.length - 1];
while (l >= indentMap.length) {
current += indentation;
indentMap.push(current);
}
}
entry.message = indentMap[l] + entry.message.split(/\n/).join('\n' + indentMap[l]);
return entry;
}));
}
}
exports.IndentLogger = IndentLogger;
//# sourceMappingURL=indent.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"indent.js","sourceRoot":"","sources":["indent.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,+BAA2B;AAC3B,qCAAkC;AAElC;;;;;;GAMG;AACH,MAAM,cAAc,GAA4C,EAAE,CAAC;AAEnE,MAAa,YAAa,SAAQ,eAAM;IACtC,YAAY,IAAY,EAAE,SAAwB,IAAI,EAAE,WAAW,GAAG,IAAI;QACxE,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAEpB,cAAc,CAAC,WAAW,CAAC,GAAG,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAClE,MAAM,SAAS,GAAG,cAAc,CAAC,WAAW,CAAC,CAAC;QAE9C,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CACtC,IAAA,UAAG,EAAC,CAAC,KAAK,EAAE,EAAE;YACZ,MAAM,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;YAC/C,IAAI,CAAC,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;gBAC1B,IAAI,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;gBAC9C,OAAO,CAAC,IAAI,SAAS,CAAC,MAAM,EAAE,CAAC;oBAC7B,OAAO,IAAI,WAAW,CAAC;oBACvB,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBAC1B,CAAC;YACH,CAAC;YAED,KAAK,CAAC,OAAO,GAAG,SAAS,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;YAEnF,OAAO,KAAK,CAAC;QACf,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;CACF;AAxBD,oCAwBC"}
+12
View File
@@ -0,0 +1,12 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './indent';
export * from './level';
export * from './logger';
export * from './null-logger';
export * from './transform-logger';
+29
View File
@@ -0,0 +1,29 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./indent"), exports);
__exportStar(require("./level"), exports);
__exportStar(require("./logger"), exports);
__exportStar(require("./null-logger"), exports);
__exportStar(require("./transform-logger"), exports);
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;;;;;;;;;;;;AAEH,2CAAyB;AACzB,0CAAwB;AACxB,2CAAyB;AACzB,gDAA8B;AAC9B,qDAAmC"}
+28
View File
@@ -0,0 +1,28 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { JsonObject } from '../json/utils';
import { LogLevel, Logger } from './logger';
export declare class LevelTransformLogger extends Logger {
readonly name: string;
readonly parent: Logger | null;
readonly levelTransform: (level: LogLevel) => LogLevel;
constructor(name: string, parent: Logger | null, levelTransform: (level: LogLevel) => LogLevel);
log(level: LogLevel, message: string, metadata?: JsonObject): void;
createChild(name: string): Logger;
}
export declare class LevelCapLogger extends LevelTransformLogger {
readonly name: string;
readonly parent: Logger | null;
readonly levelCap: LogLevel;
static levelMap: {
[cap: string]: {
[level: string]: string;
};
};
constructor(name: string, parent: Logger | null, levelCap: LogLevel);
}
+51
View File
@@ -0,0 +1,51 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.LevelCapLogger = exports.LevelTransformLogger = void 0;
const logger_1 = require("./logger");
class LevelTransformLogger extends logger_1.Logger {
name;
parent;
levelTransform;
constructor(name, parent, levelTransform) {
super(name, parent);
this.name = name;
this.parent = parent;
this.levelTransform = levelTransform;
}
log(level, message, metadata = {}) {
return super.log(this.levelTransform(level), message, metadata);
}
createChild(name) {
return new LevelTransformLogger(name, this, this.levelTransform);
}
}
exports.LevelTransformLogger = LevelTransformLogger;
class LevelCapLogger extends LevelTransformLogger {
name;
parent;
levelCap;
static levelMap = {
debug: { debug: 'debug', info: 'debug', warn: 'debug', error: 'debug', fatal: 'debug' },
info: { debug: 'debug', info: 'info', warn: 'info', error: 'info', fatal: 'info' },
warn: { debug: 'debug', info: 'info', warn: 'warn', error: 'warn', fatal: 'warn' },
error: { debug: 'debug', info: 'info', warn: 'warn', error: 'error', fatal: 'error' },
fatal: { debug: 'debug', info: 'info', warn: 'warn', error: 'error', fatal: 'fatal' },
};
constructor(name, parent, levelCap) {
super(name, parent, (level) => {
return (LevelCapLogger.levelMap[levelCap][level] || level);
});
this.name = name;
this.parent = parent;
this.levelCap = levelCap;
}
}
exports.LevelCapLogger = LevelCapLogger;
//# sourceMappingURL=level.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"level.js","sourceRoot":"","sources":["level.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAGH,qCAA4C;AAE5C,MAAa,oBAAqB,SAAQ,eAAM;IAEnB;IACA;IACT;IAHlB,YAC2B,IAAY,EACZ,MAAqB,EAC9B,cAA6C;QAE7D,KAAK,CA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AE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE;KACtF,CAAC;IAEF,YAC2B,IAAY,EACZ,MAAqB,EAC9B,QAAkB;QAElC,KAAK,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,KAAe,EAAE,EAAE;YACtC,OAAO,CAAC,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,IAAI,KAAK,CAAa,CAAC;QACzE,CAAC,CAAC,CAAC;QANsB,SAAI,GAAJ,IAAI,CAAQ;QACZ,WAAM,GAAN,MAAM,CAAe;QAC9B,aAAQ,GAAR,QAAQ,CAAU;IAKpC,CAAC;;AAjBH,wCAkBC"}
+55
View File
@@ -0,0 +1,55 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Observable, Operator, PartialObserver, Subject, Subscription } from 'rxjs';
import { JsonObject } from '../json/utils';
export interface LoggerMetadata extends JsonObject {
name: string;
path: string[];
}
export interface LogEntry extends LoggerMetadata {
level: LogLevel;
message: string;
timestamp: number;
}
export interface LoggerApi {
createChild(name: string): Logger;
log(level: LogLevel, message: string, metadata?: JsonObject): void;
debug(message: string, metadata?: JsonObject): void;
info(message: string, metadata?: JsonObject): void;
warn(message: string, metadata?: JsonObject): void;
error(message: string, metadata?: JsonObject): void;
fatal(message: string, metadata?: JsonObject): void;
}
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal';
export declare class Logger extends Observable<LogEntry> implements LoggerApi {
readonly name: string;
readonly parent: Logger | null;
protected readonly _subject: Subject<LogEntry>;
protected _metadata: LoggerMetadata;
private _obs;
private _subscription;
protected get _observable(): Observable<LogEntry>;
protected set _observable(v: Observable<LogEntry>);
constructor(name: string, parent?: Logger | null);
asApi(): LoggerApi;
createChild(name: string): Logger;
complete(): void;
log(level: LogLevel, message: string, metadata?: JsonObject): void;
next(entry: LogEntry): void;
debug(message: string, metadata?: JsonObject): void;
info(message: string, metadata?: JsonObject): void;
warn(message: string, metadata?: JsonObject): void;
error(message: string, metadata?: JsonObject): void;
fatal(message: string, metadata?: JsonObject): void;
toString(): string;
lift<R>(operator: Operator<LogEntry, R>): Observable<R>;
subscribe(): Subscription;
subscribe(observer: PartialObserver<LogEntry>): Subscription;
subscribe(next?: (value: LogEntry) => void, error?: (error: Error) => void, complete?: () => void): Subscription;
forEach(next: (value: LogEntry) => void, promiseCtor?: PromiseConstructorLike): Promise<void>;
}
+123
View File
@@ -0,0 +1,123 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = void 0;
const rxjs_1 = require("rxjs");
class Logger extends rxjs_1.Observable {
name;
parent;
_subject = new rxjs_1.Subject();
_metadata;
_obs = rxjs_1.EMPTY;
_subscription = null;
get _observable() {
return this._obs;
}
set _observable(v) {
if (this._subscription) {
this._subscription.unsubscribe();
}
this._obs = v;
if (this.parent) {
this._subscription = this.subscribe((value) => {
if (this.parent) {
this.parent._subject.next(value);
}
}, (error) => {
if (this.parent) {
this.parent._subject.error(error);
}
}, () => {
if (this._subscription) {
this._subscription.unsubscribe();
}
this._subscription = null;
});
}
}
constructor(name, parent = null) {
super();
this.name = name;
this.parent = parent;
const path = [];
let p = parent;
while (p) {
path.push(p.name);
p = p.parent;
}
this._metadata = { name, path };
this._observable = this._subject.asObservable();
if (this.parent && this.parent._subject) {
// When the parent completes, complete us as well.
this.parent._subject.subscribe(undefined, undefined, () => this.complete());
}
}
asApi() {
return {
createChild: (name) => this.createChild(name),
log: (level, message, metadata) => {
return this.log(level, message, metadata);
},
debug: (message, metadata) => this.debug(message, metadata),
info: (message, metadata) => this.info(message, metadata),
warn: (message, metadata) => this.warn(message, metadata),
error: (message, metadata) => this.error(message, metadata),
fatal: (message, metadata) => this.fatal(message, metadata),
};
}
createChild(name) {
return new this.constructor(name, this);
}
complete() {
this._subject.complete();
}
log(level, message, metadata = {}) {
const entry = Object.assign({}, metadata, this._metadata, {
level,
message,
timestamp: +Date.now(),
});
this._subject.next(entry);
}
next(entry) {
this._subject.next(entry);
}
debug(message, metadata = {}) {
this.log('debug', message, metadata);
}
info(message, metadata = {}) {
this.log('info', message, metadata);
}
warn(message, metadata = {}) {
this.log('warn', message, metadata);
}
error(message, metadata = {}) {
this.log('error', message, metadata);
}
fatal(message, metadata = {}) {
this.log('fatal', message, metadata);
}
toString() {
return `<Logger(${this.name})>`;
}
lift(operator) {
return this._observable.lift(operator);
}
subscribe(_observerOrNext, _error, _complete) {
// eslint-disable-next-line prefer-spread
return this._observable.subscribe.apply(this._observable,
// eslint-disable-next-line prefer-rest-params
arguments);
}
forEach(next, promiseCtor = Promise) {
return this._observable.forEach(next, promiseCtor);
}
}
exports.Logger = Logger;
//# sourceMappingURL=logger.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"logger.js","sourceRoot":"","sources":["logger.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,+BAA2F;AAwB3F,MAAa,MAAO,SAAQ,iBAAoB;IAsC5B;IACA;IAtCC,QAAQ,GAAsB,IAAI,cAAO,EAAY,CAAC;IAC/D,SAAS,CAAiB;IAE5B,IAAI,GAAyB,YAAK,CAAC;IACnC,aAAa,GAAwB,IAAI,CAAC;IAElD,IAAc,WAAW;QACvB,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IACD,IAAc,WAAW,CAAC,CAAuB;QAC/C,IAAI,IAAI,CAAC,aAAa,EAAE,CAAC;YACvB,IAAI,CAAC,aAAa,CAAC,WAAW,EAAE,CAAC;QACnC,CAAC;QACD,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC;QACd,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;YAChB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,SAAS,CACjC,CAAC,KAAe,EAAE,EAAE;gBAClB,IAAI,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ACJ,CAAC;IAEQ,OAAO,CACd,IAA+B,EAC/B,cAAsC,OAAO;QAE7C,OAAO,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IACrD,CAAC;CACF;AA7ID,wBA6IC"}
+12
View File
@@ -0,0 +1,12 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Logger, LoggerApi } from './logger';
export declare class NullLogger extends Logger {
constructor(parent?: Logger | null);
asApi(): LoggerApi;
}
+31
View File
@@ -0,0 +1,31 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.NullLogger = void 0;
const rxjs_1 = require("rxjs");
const logger_1 = require("./logger");
class NullLogger extends logger_1.Logger {
constructor(parent = null) {
super('', parent);
this._observable = rxjs_1.EMPTY;
}
asApi() {
return {
createChild: () => new NullLogger(this),
log() { },
debug() { },
info() { },
warn() { },
error() { },
fatal() { },
};
}
}
exports.NullLogger = NullLogger;
//# sourceMappingURL=null-logger.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"null-logger.js","sourceRoot":"","sources":["null-logger.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,+BAA6B;AAC7B,qCAA6C;AAE7C,MAAa,UAAW,SAAQ,eAAM;IACpC,YAAY,SAAwB,IAAI;QACtC,KAAK,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;QAClB,IAAI,CAAC,WAAW,GAAG,YAAK,CAAC;IAC3B,CAAC;IAEQ,KAAK;QACZ,OAAO;YACL,WAAW,EAAE,GAAG,EAAE,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC;YACvC,GAAG,KAAI,CAAC;YACR,KAAK,KAAI,CAAC;YACV,IAAI,KAAI,CAAC;YACT,IAAI,KAAI,CAAC;YACT,KAAK,KAAI,CAAC;YACV,KAAK,KAAI,CAAC;SACE,CAAC;IACjB,CAAC;CACF;AAjBD,gCAiBC"}
+12
View File
@@ -0,0 +1,12 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Observable } from 'rxjs';
import { LogEntry, Logger } from './logger';
export declare class TransformLogger extends Logger {
constructor(name: string, transform: (stream: Observable<LogEntry>) => Observable<LogEntry>, parent?: Logger | null);
}
+19
View File
@@ -0,0 +1,19 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransformLogger = void 0;
const logger_1 = require("./logger");
class TransformLogger extends logger_1.Logger {
constructor(name, transform, parent = null) {
super(name, parent);
this._observable = transform(this._observable);
}
}
exports.TransformLogger = TransformLogger;
//# sourceMappingURL=transform-logger.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"transform-logger.js","sourceRoot":"","sources":["transform-logger.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAGH,qCAA4C;AAE5C,MAAa,eAAgB,SAAQ,eAAM;IACzC,YACE,IAAY,EACZ,SAAiE,EACjE,SAAwB,IAAI;QAE5B,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACpB,IAAI,CAAC,WAAW,GAAG,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACjD,CAAC;CACF;AATD,0CASC"}
+15
View File
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as tags from './literals';
import * as strings from './strings';
export * from './object';
export * from './template';
export * from './partially-ordered-set';
export * from './priority-queue';
export * from './lang';
export { tags, strings };
+56
View File
@@ -0,0 +1,56 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.strings = exports.tags = void 0;
const tags = __importStar(require("./literals"));
exports.tags = tags;
const strings = __importStar(require("./strings"));
exports.strings = strings;
__exportStar(require("./object"), exports);
__exportStar(require("./template"), exports);
__exportStar(require("./partially-ordered-set"), exports);
__exportStar(require("./priority-queue"), exports);
__exportStar(require("./lang"), exports);
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,iDAAmC;AAS1B,oBAAI;AARb,mDAAqC;AAQtB,0BAAO;AANtB,2CAAyB;AACzB,6CAA2B;AAC3B,0DAAwC;AACxC,mDAAiC;AACjC,yCAAuB"}
+11
View File
@@ -0,0 +1,11 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Determine if the argument is shaped like a Promise
*/
export declare function isPromise(obj: any): obj is Promise<any>;
+21
View File
@@ -0,0 +1,21 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPromise = isPromise;
// Borrowed from @angular/core
/**
* Determine if the argument is shaped like a Promise
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isPromise(obj) {
// allow any Promise/A+ compliant thenable.
// It's up to the caller to ensure that obj.then conforms to the spec
return !!obj && typeof obj.then === 'function';
}
//# sourceMappingURL=lang.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"lang.js","sourceRoot":"","sources":["lang.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAQH,8BAIC;AAVD,8BAA8B;AAE9B;;GAEG;AACH,8DAA8D;AAC9D,SAAgB,SAAS,CAAC,GAAQ;IAChC,2CAA2C;IAC3C,qEAAqE;IACrE,OAAO,CAAC,CAAC,GAAG,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,UAAU,CAAC;AACjD,CAAC"}
+15
View File
@@ -0,0 +1,15 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export interface TemplateTag<R = string> {
(template: TemplateStringsArray, ...substitutions: any[]): R;
}
export declare function oneLine(strings: TemplateStringsArray, ...values: any[]): string;
export declare function indentBy(indentations: number): TemplateTag;
export declare function stripIndent(strings: TemplateStringsArray, ...values: any[]): string;
export declare function stripIndents(strings: TemplateStringsArray, ...values: any[]): string;
export declare function trimNewlines(strings: TemplateStringsArray, ...values: any[]): string;
+59
View File
@@ -0,0 +1,59 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.oneLine = oneLine;
exports.indentBy = indentBy;
exports.stripIndent = stripIndent;
exports.stripIndents = stripIndents;
exports.trimNewlines = trimNewlines;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function oneLine(strings, ...values) {
const endResult = String.raw(strings, ...values);
return endResult.replace(/(?:\r?\n(?:\s*))+/gm, ' ').trim();
}
function indentBy(indentations) {
let i = '';
while (indentations--) {
i += ' ';
}
return (strings, ...values) => {
return i + stripIndent(strings, ...values).replace(/\n/g, '\n' + i);
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function stripIndent(strings, ...values) {
const endResult = String.raw(strings, ...values);
// remove the shortest leading indentation from each line
const match = endResult.match(/^[ \t]*(?=\S)/gm);
// return early if there's nothing to strip
if (match === null) {
return endResult;
}
const indent = Math.min(...match.map((el) => el.length));
const regexp = new RegExp('^[ \\t]{' + indent + '}', 'gm');
return (indent > 0 ? endResult.replace(regexp, '') : endResult).trim();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function stripIndents(strings, ...values) {
return String.raw(strings, ...values)
.split('\n')
.map((line) => line.trim())
.join('\n')
.trim();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function trimNewlines(strings, ...values) {
const endResult = String.raw(strings, ...values);
return (endResult
// Remove the newline at the start.
.replace(/^(?:\r?\n)+/, '')
// Remove the newline at the end and following whitespace.
.replace(/(?:\r?\n(?:\s*))$/, ''));
}
//# sourceMappingURL=literals.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"literals.js","s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M,CAAC,UAAU,GAAG,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,CAAC;IAE3D,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,CAAC;AACzE,CAAC;AAED,8DAA8D;AAC9D,SAAgB,YAAY,CAAC,OAA6B,EAAE,GAAG,MAAa;IAC1E,OAAO,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,MAAM,CAAC;SAClC,KAAK,CAAC,IAAI,CAAC;SACX,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;SAC1B,IAAI,CAAC,IAAI,CAAC;SACV,IAAI,EAAE,CAAC;AACZ,CAAC;AAED,8DAA8D;AAC9D,SAAgB,YAAY,CAAC,OAA6B,EAAE,GAAG,MAAa;IAC1E,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,MAAM,CAAC,CAAC;IAEjD,OAAO,CACL,SAAS;QACP,mCAAmC;SAClC,OAAO,CAAC,aAAa,EAAE,EAAE,CAAC;QAC3B,0DAA0D;SACzD,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC,CACpC,CAAC;AACJ,CAAC"}
+8
View File
@@ -0,0 +1,8 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export declare function deepCopy<T>(value: T): T;
+37
View File
@@ -0,0 +1,37 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.deepCopy = deepCopy;
const copySymbol = Symbol();
function deepCopy(value) {
if (Array.isArray(value)) {
return value.map((o) => deepCopy(o));
}
else if (value && typeof value === 'object') {
const valueCasted = value;
if (valueCasted[copySymbol]) {
// This is a circular dependency. Just return the cloned value.
return valueCasted[copySymbol];
}
if (valueCasted['toJSON']) {
return JSON.parse(valueCasted['toJSON']());
}
const copy = Object.create(Object.getPrototypeOf(valueCasted));
valueCasted[copySymbol] = copy;
for (const key of Object.getOwnPropertyNames(valueCasted)) {
copy[key] = deepCopy(valueCasted[key]);
}
delete valueCasted[copySymbol];
return copy;
}
else {
return value;
}
}
//# sourceMappingURL=object.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"object.js","sourceRoot":"","sources":["object.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAIH,4BA+BC;AAjCD,MAAM,UAAU,GAAG,MAAM,EAAE,CAAC;AAE5B,SAAgB,QAAQ,CAAI,KAAQ;IAClC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAiB,CAAC;IACvD,CAAC;SAAM,IAAI,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC9C,MAAM,WAAW,GAAG,KAKnB,CAAC;QAEF,IAAI,WAAW,CAAC,UAAU,CAAC,EAAE,CAAC;YAC5B,+DAA+D;YAC/D,OAAO,WAAW,CAAC,UAAU,CAAM,CAAC;QACtC,CAAC;QAED,IAAI,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC1B,OAAO,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,CAAM,CAAC;QAClD,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,CAAC,CAAC;QAC/D,WAAW,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC;QAC/B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,mBAAmB,CAAC,WAAW,CAAC,EAAE,CAAC;YAC1D,IAAI,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC;QACzC,CAAC;QACD,OAAO,WAAW,CAAC,UAAU,CAAC,CAAC;QAE/B,OAAO,IAAI,CAAC;IACd,CAAC;SAAM,CAAC;QACN,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC"}
+38
View File
@@ -0,0 +1,38 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { BaseException } from '../exception';
export declare class DependencyNotFoundException extends BaseException {
constructor();
}
export declare class CircularDependencyFoundException extends BaseException {
constructor();
}
export declare class PartiallyOrderedSet<T> {
private _items;
protected _checkCircularDependencies(item: T, deps: Set<T>): void;
clear(): void;
has(item: T): boolean;
get size(): number;
forEach(callbackfn: (value: T, value2: T, set: PartiallyOrderedSet<T>) => void, thisArg?: any): void;
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
entries(): IterableIterator<[T, T]>;
/**
* Despite its name, returns an iterable of the values in the set,
*/
keys(): IterableIterator<T>;
/**
* Returns an iterable of values in the set.
*/
values(): IterableIterator<T>;
add(item: T, deps?: Set<T> | T[]): this;
delete(item: T): boolean;
[Symbol.iterator](): IterableIterator<T, undefined, unknown>;
get [Symbol.toStringTag](): 'PartiallyOrderedSet';
}
+145
View File
@@ -0,0 +1,145 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PartiallyOrderedSet = exports.CircularDependencyFoundException = exports.DependencyNotFoundException = void 0;
const exception_1 = require("../exception");
class DependencyNotFoundException extends exception_1.BaseException {
constructor() {
super('One of the dependencies is not part of the set.');
}
}
exports.DependencyNotFoundException = DependencyNotFoundException;
class CircularDependencyFoundException extends exception_1.BaseException {
constructor() {
super('Circular dependencies found.');
}
}
exports.CircularDependencyFoundException = CircularDependencyFoundException;
class PartiallyOrderedSet {
_items = new Map();
_checkCircularDependencies(item, deps) {
if (deps.has(item)) {
throw new CircularDependencyFoundException();
}
deps.forEach((dep) => this._checkCircularDependencies(item, this._items.get(dep) || new Set()));
}
clear() {
this._items.clear();
}
has(item) {
return this._items.has(item);
}
get size() {
return this._items.size;
}
forEach(callbackfn, thisArg) {
for (const x of this) {
callbackfn.call(thisArg, x, x, this);
}
}
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
*entries() {
for (const item of this) {
yield [item, item];
}
}
/**
* Despite its name, returns an iterable of the values in the set,
*/
keys() {
return this.values();
}
/**
* Returns an iterable of values in the set.
*/
values() {
return this[Symbol.iterator]();
}
add(item, deps = new Set()) {
if (Array.isArray(deps)) {
deps = new Set(deps);
}
// Verify item is not already in the set.
if (this._items.has(item)) {
const itemDeps = this._items.get(item) || new Set();
// If the dependency list is equal, just return, otherwise remove and keep going.
let equal = true;
for (const dep of deps) {
if (!itemDeps.has(dep)) {
equal = false;
break;
}
}
if (equal) {
for (const dep of itemDeps) {
if (!deps.has(dep)) {
equal = false;
break;
}
}
}
if (equal) {
return this;
}
else {
this._items.delete(item);
}
}
// Verify all dependencies are part of the Set.
for (const dep of deps) {
if (!this._items.has(dep)) {
throw new DependencyNotFoundException();
}
}
// Verify there's no dependency cycle.
this._checkCircularDependencies(item, deps);
this._items.set(item, new Set(deps));
return this;
}
delete(item) {
if (!this._items.has(item)) {
return false;
}
// Remove it from all dependencies if force == true.
this._items.forEach((value) => value.delete(item));
return this._items.delete(item);
}
*[Symbol.iterator]() {
const copy = new Map(this._items);
for (const [key, value] of copy.entries()) {
copy.set(key, new Set(value));
}
while (copy.size > 0) {
const run = [];
// Take the first item without dependencies.
for (const [item, deps] of copy.entries()) {
if (deps.size == 0) {
run.push(item);
}
}
for (const item of run) {
copy.forEach((s) => s.delete(item));
copy.delete(item);
yield item;
}
if (run.length == 0) {
// uh oh...
throw new CircularDependencyFoundException();
}
}
return undefined;
}
get [Symbol.toStringTag]() {
return 'PartiallyOrderedSet';
}
}
exports.PartiallyOrderedSet = PartiallyOrderedSet;
//# sourceMappingURL=partially-ordered-set.js.map
@@ -0,0 +1 @@
{"version":3,"file":"partially-ordered-set.js","sourceRoot":"","sources":["partially-ordered-set.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,4CAA6C;AAE7C,MAAa,2BAA4B,SAAQ,yBAAa;IAC5D;QACE,KAAK,CAAC,iDAAiD,CAAC,CAAC;IAC3D,CAAC;CACF;AAJD,kEAIC;AACD,MAAa,gCAAiC,SAAQ,yBAAa;IACjE;QACE,KAAK,CAAC,8BAA8B,CAAC,CAAC;IACxC,CAAC;CACF;AAJD,4EAIC;AAED,MAAa,mBAAmB;IACtB,MAAM,GAAG,IAAI,GAAG,EAAa,CAAC;IAE5B,0BAA0B,CAAC,IAAO,EAAE,IAAY;QACxD,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YACnB,MAAM,IAAI,gCAAgC,EAAE,CAAC;QAC/C,CAAC;QAED,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,0BAA0B,CAAC,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,GAAG,EAAE,CAAC,CAAC,CAAC;IAClG,CAAC;IAED,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;IACD,GAAG,CAAC,IAAO;QACT,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IACD,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;IAC1B,CAAC;IACD,OAAO,CACL,UAAsE,EACtE,OAAa;QAEb,KAAK,M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,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC;QAChC,CAAC;QAED,OAAO,IAAI,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;YACrB,MAAM,GAAG,GAAQ,EAAE,CAAC;YACpB,4CAA4C;YAC5C,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,CAAC;gBAC1C,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,EAAE,CAAC;oBACnB,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBACjB,CAAC;YACH,CAAC;YAED,KAAK,MAAM,IAAI,IAAI,GAAG,EAAE,CAAC;gBACvB,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;gBACpC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;gBAClB,MAAM,IAAI,CAAC;YACb,CAAC;YAED,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,EAAE,CAAC;gBACpB,WAAW;gBACX,MAAM,IAAI,gCAAgC,EAAE,CAAC;YAC/C,CAAC;QACH,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACtB,OAAO,qBAAqB,CAAC;IAC/B,CAAC;CACF;AAjJD,kDAiJC"}
+19
View File
@@ -0,0 +1,19 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/** Naive priority queue; not intended for large datasets */
export declare class PriorityQueue<T> {
private _comparator;
private _items;
constructor(_comparator: (x: T, y: T) => number);
clear(): void;
push(item: T): void;
pop(): T | undefined;
peek(): T | undefined;
get size(): number;
toArray(): Array<T>;
}
+50
View File
@@ -0,0 +1,50 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PriorityQueue = void 0;
/** Naive priority queue; not intended for large datasets */
class PriorityQueue {
_comparator;
_items = new Array();
constructor(_comparator) {
this._comparator = _comparator;
}
clear() {
this._items = new Array();
}
push(item) {
const index = this._items.findIndex((existing) => this._comparator(item, existing) <= 0);
if (index === -1) {
this._items.push(item);
}
else {
this._items.splice(index, 0, item);
}
}
pop() {
if (this._items.length === 0) {
return undefined;
}
return this._items.splice(0, 1)[0];
}
peek() {
if (this._items.length === 0) {
return undefined;
}
return this._items[0];
}
get size() {
return this._items.length;
}
toArray() {
return this._items.slice();
}
}
exports.PriorityQueue = PriorityQueue;
//# sourceMappingURL=priority-queue.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"priority-queue.js","sourceRoot":"","sources":["priority-queue.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,4DAA4D;AAC5D,MAAa,aAAa;IAGJ;IAFZ,MAAM,GAAG,IAAI,KAAK,EAAK,CAAC;IAEhC,YAAoB,WAAmC;QAAnC,gBAAW,GAAX,WAAW,CAAwB;IAAG,CAAC;IAE3D,KAAK;QACH,IAAI,CAAC,MAAM,GAAG,IAAI,KAAK,EAAK,CAAC;IAC/B,CAAC;IAED,IAAI,CAAC,IAAO;QACV,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;QAEzF,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;YACjB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzB,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC;QACrC,CAAC;IACH,CAAC;IAED,GAAG;QACD,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC7B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrC,CAAC;IAED,IAAI;QACF,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC7B,OAAO,SAAS,CAAC;QACnB,CAAC;QAED,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACxB,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;IAC5B,CAAC;IAED,OAAO;QACL,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IAC7B,CAAC;CACF;AA1CD,sCA0CC"}
+112
View File
@@ -0,0 +1,112 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* Converts a camelized string into all lower case separated by underscores.
*
```javascript
decamelize('innerHTML'); // 'inner_html'
decamelize('action_name'); // 'action_name'
decamelize('css-class-name'); // 'css-class-name'
decamelize('my favorite items'); // 'my favorite items'
```
@method decamelize
@param {String} str The string to decamelize.
@return {String} the decamelized string.
*/
export declare function decamelize(str: string): string;
/**
Replaces underscores, spaces, or camelCase with dashes.
```javascript
dasherize('innerHTML'); // 'inner-html'
dasherize('action_name'); // 'action-name'
dasherize('css-class-name'); // 'css-class-name'
dasherize('my favorite items'); // 'my-favorite-items'
```
@method dasherize
@param {String} str The string to dasherize.
@return {String} the dasherized string.
*/
export declare function dasherize(str: string): string;
/**
Returns the lowerCamelCase form of a string.
```javascript
camelize('innerHTML'); // 'innerHTML'
camelize('action_name'); // 'actionName'
camelize('css-class-name'); // 'cssClassName'
camelize('my favorite items'); // 'myFavoriteItems'
camelize('My Favorite Items'); // 'myFavoriteItems'
```
@method camelize
@param {String} str The string to camelize.
@return {String} the camelized string.
*/
export declare function camelize(str: string): string;
/**
Returns the UpperCamelCase form of a string.
@example
```javascript
'innerHTML'.classify(); // 'InnerHTML'
'action_name'.classify(); // 'ActionName'
'css-class-name'.classify(); // 'CssClassName'
'my favorite items'.classify(); // 'MyFavoriteItems'
'app.component'.classify(); // 'AppComponent'
```
@method classify
@param {String} str the string to classify
@return {String} the classified string
*/
export declare function classify(str: string): string;
/**
More general than decamelize. Returns the lower_case_and_underscored
form of a string.
```javascript
'innerHTML'.underscore(); // 'inner_html'
'action_name'.underscore(); // 'action_name'
'css-class-name'.underscore(); // 'css_class_name'
'my favorite items'.underscore(); // 'my_favorite_items'
```
@method underscore
@param {String} str The string to underscore.
@return {String} the underscored string.
*/
export declare function underscore(str: string): string;
/**
Returns the Capitalized form of a string
```javascript
'innerHTML'.capitalize() // 'InnerHTML'
'action_name'.capitalize() // 'Action_name'
'css-class-name'.capitalize() // 'Css-class-name'
'my favorite items'.capitalize() // 'My favorite items'
```
@method capitalize
@param {String} str The string to capitalize.
@return {String} The capitalized string.
*/
export declare function capitalize(str: string): string;
/**
* Calculate the levenshtein distance of two strings.
* See https://en.wikipedia.org/wiki/Levenshtein_distance.
* Based off https://gist.github.com/andrei-m/982927 (for using the faster dynamic programming
* version).
*
* @param a String a.
* @param b String b.
* @returns A number that represents the distance between the two strings. The greater the number
* the more distant the strings are from each others.
*/
export declare function levenshtein(a: string, b: string): number;
+179
View File
@@ -0,0 +1,179 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.decamelize = decamelize;
exports.dasherize = dasherize;
exports.camelize = camelize;
exports.classify = classify;
exports.underscore = underscore;
exports.capitalize = capitalize;
exports.levenshtein = levenshtein;
const STRING_DASHERIZE_REGEXP = /[ _]/g;
const STRING_DECAMELIZE_REGEXP = /([a-z\d])([A-Z])/g;
const STRING_CAMELIZE_REGEXP = /(-|_|\.|\s)+(.)?/g;
const STRING_UNDERSCORE_REGEXP_1 = /([a-z\d])([A-Z]+)/g;
const STRING_UNDERSCORE_REGEXP_2 = /-|\s+/g;
/**
* Converts a camelized string into all lower case separated by underscores.
*
```javascript
decamelize('innerHTML'); // 'inner_html'
decamelize('action_name'); // 'action_name'
decamelize('css-class-name'); // 'css-class-name'
decamelize('my favorite items'); // 'my favorite items'
```
@method decamelize
@param {String} str The string to decamelize.
@return {String} the decamelized string.
*/
function decamelize(str) {
return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase();
}
/**
Replaces underscores, spaces, or camelCase with dashes.
```javascript
dasherize('innerHTML'); // 'inner-html'
dasherize('action_name'); // 'action-name'
dasherize('css-class-name'); // 'css-class-name'
dasherize('my favorite items'); // 'my-favorite-items'
```
@method dasherize
@param {String} str The string to dasherize.
@return {String} the dasherized string.
*/
function dasherize(str) {
return decamelize(str).replace(STRING_DASHERIZE_REGEXP, '-');
}
/**
Returns the lowerCamelCase form of a string.
```javascript
camelize('innerHTML'); // 'innerHTML'
camelize('action_name'); // 'actionName'
camelize('css-class-name'); // 'cssClassName'
camelize('my favorite items'); // 'myFavoriteItems'
camelize('My Favorite Items'); // 'myFavoriteItems'
```
@method camelize
@param {String} str The string to camelize.
@return {String} the camelized string.
*/
function camelize(str) {
return str
.replace(STRING_CAMELIZE_REGEXP, (_match, _separator, chr) => {
return chr ? chr.toUpperCase() : '';
})
.replace(/^([A-Z])/, (match) => match.toLowerCase());
}
/**
Returns the UpperCamelCase form of a string.
@example
```javascript
'innerHTML'.classify(); // 'InnerHTML'
'action_name'.classify(); // 'ActionName'
'css-class-name'.classify(); // 'CssClassName'
'my favorite items'.classify(); // 'MyFavoriteItems'
'app.component'.classify(); // 'AppComponent'
```
@method classify
@param {String} str the string to classify
@return {String} the classified string
*/
function classify(str) {
return str
.split('.')
.map((part) => capitalize(camelize(part)))
.join('');
}
/**
More general than decamelize. Returns the lower_case_and_underscored
form of a string.
```javascript
'innerHTML'.underscore(); // 'inner_html'
'action_name'.underscore(); // 'action_name'
'css-class-name'.underscore(); // 'css_class_name'
'my favorite items'.underscore(); // 'my_favorite_items'
```
@method underscore
@param {String} str The string to underscore.
@return {String} the underscored string.
*/
function underscore(str) {
return str
.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2')
.replace(STRING_UNDERSCORE_REGEXP_2, '_')
.toLowerCase();
}
/**
Returns the Capitalized form of a string
```javascript
'innerHTML'.capitalize() // 'InnerHTML'
'action_name'.capitalize() // 'Action_name'
'css-class-name'.capitalize() // 'Css-class-name'
'my favorite items'.capitalize() // 'My favorite items'
```
@method capitalize
@param {String} str The string to capitalize.
@return {String} The capitalized string.
*/
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
/**
* Calculate the levenshtein distance of two strings.
* See https://en.wikipedia.org/wiki/Levenshtein_distance.
* Based off https://gist.github.com/andrei-m/982927 (for using the faster dynamic programming
* version).
*
* @param a String a.
* @param b String b.
* @returns A number that represents the distance between the two strings. The greater the number
* the more distant the strings are from each others.
*/
function levenshtein(a, b) {
if (a.length == 0) {
return b.length;
}
if (b.length == 0) {
return a.length;
}
const matrix = [];
// increment along the first column of each row
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
// increment each column in the first row
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
// Fill in the rest of the matrix
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) == a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
}
else {
matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
matrix[i][j - 1] + 1, // insertion
matrix[i - 1][j] + 1);
}
}
}
return matrix[b.length][a.length];
}
//# sourceMappingURL=strings.js.map
+1
View File
@@ -0,0 +1 @@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,EAAE,CAAC,EAAE,EAAE,CAAC;QACnC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACnC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;gBACvC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACtC,CAAC;iBAAM,CAAC;gBACN,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,GAAG,CACrB,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,EAAE,eAAe;gBACzC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,EAAE,YAAY;gBAClC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CACrB,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;AACpC,CAAC"}
+89
View File
@@ -0,0 +1,89 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Position } from 'source-map';
export interface TemplateOptions {
sourceURL?: string;
sourceMap?: boolean;
module?: boolean | {
exports: {};
};
sourceRoot?: string;
fileName?: string;
}
/**
* A simple AST for templates. There's only one level of AST nodes, but it's still useful
* to have the information you're looking for.
*/
export interface TemplateAst {
fileName: string;
content: string;
children: TemplateAstNode[];
}
/**
* The base, which contains positions.
*/
export interface TemplateAstBase {
start: Position;
end: Position;
}
/**
* A static content node.
*/
export interface TemplateAstContent extends TemplateAstBase {
kind: 'content';
content: string;
}
/**
* A comment node.
*/
export interface TemplateAstComment extends TemplateAstBase {
kind: 'comment';
text: string;
}
/**
* An evaluate node, which is the code between `<% ... %>`.
*/
export interface TemplateAstEvaluate extends TemplateAstBase {
kind: 'evaluate';
expression: string;
}
/**
* An escape node, which is the code between `<%- ... %>`.
*/
export interface TemplateAstEscape extends TemplateAstBase {
kind: 'escape';
expression: string;
}
/**
* An interpolation node, which is the code between `<%= ... %>`.
*/
export interface TemplateAstInterpolate extends TemplateAstBase {
kind: 'interpolate';
expression: string;
}
export type TemplateAstNode = TemplateAstContent | TemplateAstEvaluate | TemplateAstComment | TemplateAstEscape | TemplateAstInterpolate;
/**
* Given a source text (and a fileName), returns a TemplateAst.
*/
export declare function templateParser(sourceText: string, fileName: string): TemplateAst;
/**
* An equivalent of EJS templates, which is based on John Resig's `tmpl` implementation
* (http://ejohn.org/blog/javascript-micro-templating/) and Laura Doktorova's doT.js
* (https://github.com/olado/doT).
*
* This version differs from lodash by removing support from ES6 quasi-literals, and making the
* code slightly simpler to follow. It also does not depend on any third party, which is nice.
*
* Finally, it supports SourceMap, if you ever need to debug, which is super nice.
*
* @param content The template content.
* @param options Optional Options. See TemplateOptions for more description.
* @return {(input: T) => string} A function that accept an input object and returns the content
* of the template with the input applied.
*/
export declare function template<T>(content: string, options?: TemplateOptions): (input: T) => string;
+260
View File
@@ -0,0 +1,260 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.templateParser = templateParser;
exports.template = template;
const source_map_1 = require("source-map");
// Matches <%= expr %>. This does not support structural JavaScript (for/if/...).
const kInterpolateRe = /<%=([\s\S]+?)%>/g;
// Matches <%# text %>. It's a comment and will be entirely ignored.
const kCommentRe = /<%#([\s\S]+?)%>/g;
// Used to match template delimiters.
// <%- expr %>: HTML escape the value.
// <% ... %>: Structural template code.
const kEscapeRe = /<%-([\s\S]+?)%>/g;
const kEvaluateRe = /<%([\s\S]+?)%>/g;
/** Used to map characters to HTML entities. */
const kHtmlEscapes = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
'`': '&#96;',
};
// Used to match HTML entities and HTML characters.
const reUnescapedHtml = new RegExp(`[${Object.keys(kHtmlEscapes).join('')}]`, 'g');
function _positionFor(content, offset) {
let line = 1;
let column = 0;
for (let i = 0; i < offset - 1; i++) {
if (content[i] == '\n') {
line++;
column = 0;
}
else {
column++;
}
}
return {
line,
column,
};
}
/**
* Given a source text (and a fileName), returns a TemplateAst.
*/
function templateParser(sourceText, fileName) {
const children = [];
// Compile the regexp to match each delimiter.
const reExpressions = [kEscapeRe, kCommentRe, kInterpolateRe, kEvaluateRe];
const reDelimiters = RegExp(reExpressions.map((x) => x.source).join('|') + '|$', 'g');
const parsed = sourceText.split(reDelimiters);
let offset = 0;
// Optimization that uses the fact that the end of a node is always the beginning of the next
// node, so we keep the positioning of the nodes in memory.
let start = _positionFor(sourceText, offset);
let end;
const increment = reExpressions.length + 1;
for (let i = 0; i < parsed.length; i += increment) {
const [content, escape, comment, interpolate, evaluate] = parsed.slice(i, i + increment);
if (content) {
end = _positionFor(sourceText, offset + content.length);
offset += content.length;
children.push({ kind: 'content', content, start, end });
start = end;
}
if (escape) {
end = _positionFor(sourceText, offset + escape.length + 5);
offset += escape.length + 5;
children.push({ kind: 'escape', expression: escape, start, end });
start = end;
}
if (comment) {
end = _positionFor(sourceText, offset + comment.length + 5);
offset += comment.length + 5;
children.push({ kind: 'comment', text: comment, start, end });
start = end;
}
if (interpolate) {
end = _positionFor(sourceText, offset + interpolate.length + 5);
offset += interpolate.length + 5;
children.push({
kind: 'interpolate',
expression: interpolate,
start,
end,
});
start = end;
}
if (evaluate) {
end = _positionFor(sourceText, offset + evaluate.length + 5);
offset += evaluate.length + 5;
children.push({ kind: 'evaluate', expression: evaluate, start, end });
start = end;
}
}
return {
fileName,
content: sourceText,
children,
};
}
/**
* Fastest implementation of the templating algorithm. It only add strings and does not bother
* with source maps.
*/
function templateFast(ast, options) {
const module = options && options.module ? 'module.exports.default =' : '';
const reHtmlEscape = reUnescapedHtml.source.replace(/[']/g, "\\\\\\'");
return `
return ${module} function(obj) {
obj || (obj = {});
let __t;
let __p = '';
const __escapes = ${JSON.stringify(kHtmlEscapes)};
const __escapesre = new RegExp('${reHtmlEscape}', 'g');
const __e = function(s) {
return s ? s.replace(__escapesre, function(key) { return __escapes[key]; }) : '';
};
with (obj) {
${ast.children
.map((node) => {
switch (node.kind) {
case 'content':
return `__p += ${JSON.stringify(node.content)};`;
case 'interpolate':
return `__p += ((__t = (${node.expression})) == null) ? '' : __t;`;
case 'escape':
return `__p += __e(${node.expression});`;
case 'evaluate':
return node.expression;
}
})
.join('\n')}
}
return __p;
};
`;
}
/**
* Templating algorithm with source map support. The map is outputted as //# sourceMapUrl=...
*/
function templateWithSourceMap(ast, options) {
const sourceUrl = ast.fileName;
const module = options && options.module ? 'module.exports.default =' : '';
const reHtmlEscape = reUnescapedHtml.source.replace(/[']/g, "\\\\\\'");
const preamble = new source_map_1.SourceNode(1, 0, sourceUrl, '').add(new source_map_1.SourceNode(1, 0, sourceUrl, [
`return ${module} function(obj) {\n`,
' obj || (obj = {});\n',
' let __t;\n',
' let __p = "";\n',
` const __escapes = ${JSON.stringify(kHtmlEscapes)};\n`,
` const __escapesre = new RegExp('${reHtmlEscape}', 'g');\n`,
`\n`,
` const __e = function(s) { `,
` return s ? s.replace(__escapesre, function(key) { return __escapes[key]; }) : '';`,
` };\n`,
` with (obj) {\n`,
]));
const end = ast.children.at(-1)?.end ?? { line: 0, column: 0 };
const nodes = ast.children
.reduce((chunk, node) => {
let code = '';
switch (node.kind) {
case 'content':
code = [
new source_map_1.SourceNode(node.start.line, node.start.column, sourceUrl, '__p = __p'),
...node.content.split('\n').map((line, i, arr) => {
return new source_map_1.SourceNode(node.start.line + i, i == 0 ? node.start.column : 0, sourceUrl, '\n + ' + JSON.stringify(line + (i == arr.length - 1 ? '' : '\n')));
}),
new source_map_1.SourceNode(node.end.line, node.end.column, sourceUrl, ';\n'),
];
break;
case 'interpolate':
code = [
new source_map_1.SourceNode(node.start.line, node.start.column, sourceUrl, '__p += ((__t = '),
...node.expression.split('\n').map((line, i, arr) => {
return new source_map_1.SourceNode(node.start.line + i, i == 0 ? node.start.column : 0, sourceUrl, line + (i == arr.length - 1 ? '' : '\n'));
}),
new source_map_1.SourceNode(node.end.line, node.end.column, sourceUrl, ') == null ? "" : __t);\n'),
];
break;
case 'escape':
code = [
new source_map_1.SourceNode(node.start.line, node.start.column, sourceUrl, '__p += __e('),
...node.expression.split('\n').map((line, i, arr) => {
return new source_map_1.SourceNode(node.start.line + i, i == 0 ? node.start.column : 0, sourceUrl, line + (i == arr.length - 1 ? '' : '\n'));
}),
new source_map_1.SourceNode(node.end.line, node.end.column, sourceUrl, ');\n'),
];
break;
case 'evaluate':
code = [
...node.expression.split('\n').map((line, i, arr) => {
return new source_map_1.SourceNode(node.start.line + i, i == 0 ? node.start.column : 0, sourceUrl, line + (i == arr.length - 1 ? '' : '\n'));
}),
new source_map_1.SourceNode(node.end.line, node.end.column, sourceUrl, '\n'),
];
break;
}
return chunk.add(new source_map_1.SourceNode(node.start.line, node.start.column, sourceUrl, code));
}, preamble)
.add(new source_map_1.SourceNode(end.line, end.column, sourceUrl, [' };\n', '\n', ' return __p;\n', '}\n']));
const code = nodes.toStringWithSourceMap({
file: sourceUrl,
sourceRoot: (options && options.sourceRoot) || '.',
});
// Set the source content in the source map, otherwise the sourceUrl is not enough
// to find the content.
code.map.setSourceContent(sourceUrl, ast.content);
return (code.code +
'\n//# sourceMappingURL=data:application/json;base64,' +
Buffer.from(code.map.toString()).toString('base64'));
}
/**
* An equivalent of EJS templates, which is based on John Resig's `tmpl` implementation
* (http://ejohn.org/blog/javascript-micro-templating/) and Laura Doktorova's doT.js
* (https://github.com/olado/doT).
*
* This version differs from lodash by removing support from ES6 quasi-literals, and making the
* code slightly simpler to follow. It also does not depend on any third party, which is nice.
*
* Finally, it supports SourceMap, if you ever need to debug, which is super nice.
*
* @param content The template content.
* @param options Optional Options. See TemplateOptions for more description.
* @return {(input: T) => string} A function that accept an input object and returns the content
* of the template with the input applied.
*/
function template(content, options) {
const sourceUrl = (options && options.sourceURL) || 'ejs';
const ast = templateParser(content, sourceUrl);
let source;
// If there's no need for source map support, we revert back to the fast implementation.
if (options && options.sourceMap) {
source = templateWithSourceMap(ast, options);
}
else {
source = templateFast(ast, options);
}
// We pass a dummy module in case the module option is passed. If `module: true` is passed, we
// need to only use the source, not the function itself. Otherwise expect a module object to be
// passed, and we use that one.
const fn = Function('module', source);
const module = options && options.module ? (options.module === true ? { exports: {} } : options.module) : null;
const result = fn(module);
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
return result;
}
//# sourceMappingURL=template.js.map
File diff suppressed because one or more lines are too long
+60
View File
@@ -0,0 +1,60 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Path } from '../path';
import { ResolverHost } from './resolver';
/**
* A Virtual Host that allow to alias some paths to other paths.
*
* This does not verify, when setting an alias, that the target or source exist. Neither does it
* check whether it's a file or a directory. Please not that directories are also renamed/replaced.
*
* No recursion is done on the resolution, which means the following is perfectly valid then:
*
* ```
* host.aliases.set(normalize('/file/a'), normalize('/file/b'));
* host.aliases.set(normalize('/file/b'), normalize('/file/a'));
* ```
*
* This will result in a proper swap of two files for each others.
*
* @example
* const host = new SimpleMemoryHost();
* host.write(normalize('/some/file'), content).subscribe();
*
* const aHost = new AliasHost(host);
* aHost.read(normalize('/some/file'))
* .subscribe(x => expect(x).toBe(content));
* aHost.aliases.set(normalize('/some/file'), normalize('/other/path');
*
* // This file will not exist because /other/path does not exist.
* aHost.read(normalize('/some/file'))
* .subscribe(undefined, err => expect(err.message).toMatch(/does not exist/));
*
* @example
* const host = new SimpleMemoryHost();
* host.write(normalize('/some/folder/file'), content).subscribe();
*
* const aHost = new AliasHost(host);
* aHost.read(normalize('/some/folder/file'))
* .subscribe(x => expect(x).toBe(content));
* aHost.aliases.set(normalize('/some'), normalize('/other');
*
* // This file will not exist because /other/path does not exist.
* aHost.read(normalize('/some/folder/file'))
* .subscribe(undefined, err => expect(err.message).toMatch(/does not exist/));
*
* // Create the file with new content and verify that this has the new content.
* aHost.write(normalize('/other/folder/file'), content2).subscribe();
* aHost.read(normalize('/some/folder/file'))
* .subscribe(x => expect(x).toBe(content2));
*/
export declare class AliasHost<StatsT extends object = {}> extends ResolverHost<StatsT> {
protected _aliases: Map<Path, Path>;
protected _resolve(path: Path): Path;
get aliases(): Map<Path, Path>;
}
+84
View File
@@ -0,0 +1,84 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AliasHost = void 0;
const path_1 = require("../path");
const resolver_1 = require("./resolver");
/**
* A Virtual Host that allow to alias some paths to other paths.
*
* This does not verify, when setting an alias, that the target or source exist. Neither does it
* check whether it's a file or a directory. Please not that directories are also renamed/replaced.
*
* No recursion is done on the resolution, which means the following is perfectly valid then:
*
* ```
* host.aliases.set(normalize('/file/a'), normalize('/file/b'));
* host.aliases.set(normalize('/file/b'), normalize('/file/a'));
* ```
*
* This will result in a proper swap of two files for each others.
*
* @example
* const host = new SimpleMemoryHost();
* host.write(normalize('/some/file'), content).subscribe();
*
* const aHost = new AliasHost(host);
* aHost.read(normalize('/some/file'))
* .subscribe(x => expect(x).toBe(content));
* aHost.aliases.set(normalize('/some/file'), normalize('/other/path');
*
* // This file will not exist because /other/path does not exist.
* aHost.read(normalize('/some/file'))
* .subscribe(undefined, err => expect(err.message).toMatch(/does not exist/));
*
* @example
* const host = new SimpleMemoryHost();
* host.write(normalize('/some/folder/file'), content).subscribe();
*
* const aHost = new AliasHost(host);
* aHost.read(normalize('/some/folder/file'))
* .subscribe(x => expect(x).toBe(content));
* aHost.aliases.set(normalize('/some'), normalize('/other');
*
* // This file will not exist because /other/path does not exist.
* aHost.read(normalize('/some/folder/file'))
* .subscribe(undefined, err => expect(err.message).toMatch(/does not exist/));
*
* // Create the file with new content and verify that this has the new content.
* aHost.write(normalize('/other/folder/file'), content2).subscribe();
* aHost.read(normalize('/some/folder/file'))
* .subscribe(x => expect(x).toBe(content2));
*/
class AliasHost extends resolver_1.ResolverHost {
_aliases = new Map();
_resolve(path) {
let maybeAlias = this._aliases.get(path);
const sp = (0, path_1.split)(path);
const remaining = [];
// Also resolve all parents of the requested files, only picking the first one that matches.
// This can have surprising behaviour when aliases are inside another alias. It will always
// use the closest one to the file.
while (!maybeAlias && sp.length > 0) {
const p = (0, path_1.join)(path_1.NormalizedRoot, ...sp);
maybeAlias = this._aliases.get(p);
if (maybeAlias) {
maybeAlias = (0, path_1.join)(maybeAlias, ...remaining);
}
// Allow non-null-operator because we know sp.length > 0 (condition on while).
remaining.unshift(sp.pop()); // eslint-disable-line @typescript-eslint/no-non-null-assertion
}
return maybeAlias || path;
}
get aliases() {
return this._aliases;
}
}
exports.AliasHost = AliasHost;
//# sourceMappingURL=alias.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"alias.js","sourceRoot":"","sources":["alias.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,kCAA0E;AAC1E,yCAA0C;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6CG;AACH,MAAa,SAAsC,SAAQ,uBAAoB;IACnE,QAAQ,GAAoB,IAAI,GAAG,EAAE,CAAC;IAEtC,QAAQ,CAAC,IAAU;QAC3B,IAAI,UAAU,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACzC,MAAM,EAAE,GAAG,IAAA,YAAK,EAAC,IAAI,CAAC,CAAC;QACvB,MAAM,SAAS,GAAmB,EAAE,CAAC;QAErC,4FAA4F;QAC5F,2FAA2F;QAC3F,mCAAmC;QACnC,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACpC,MAAM,CAAC,GAAG,IAAA,WAAI,EAAC,qBAAc,EAAE,GAAG,EAAE,CAAC,CAAC;YACtC,UAAU,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;YAElC,IAAI,UAAU,EAAE,CAAC;gBACf,UAAU,GAAG,IAAA,WAAI,EAAC,UAAU,EAAE,GAAG,SAAS,CAAC,CAAC;YAC9C,CAAC;YACD,8EAA8E;YAC9E,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC,GAAG,EAAG,CAAC,CAAC,CAAC,+DAA+D;QAC/F,CAAC;QAED,OAAO,UAAU,IAAI,IAAI,CAAC;IAC5B,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;CACF;AA5BD,8BA4BC"}
+10
View File
@@ -0,0 +1,10 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { FileBuffer } from './interface';
export declare function stringToFileBuffer(str: string): FileBuffer;
export declare function fileBufferToString(fileBuffer: FileBuffer): string;
+22
View File
@@ -0,0 +1,22 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.stringToFileBuffer = stringToFileBuffer;
exports.fileBufferToString = fileBufferToString;
const node_util_1 = require("node:util");
function stringToFileBuffer(str) {
return new node_util_1.TextEncoder().encode(str).buffer;
}
function fileBufferToString(fileBuffer) {
if (fileBuffer.toString.length === 1) {
return fileBuffer.toString('utf-8');
}
return new node_util_1.TextDecoder('utf-8').decode(new Uint8Array(fileBuffer));
}
//# sourceMappingURL=buffer.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"buffer.js","sourceRoot":"","sources":["buffer.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AAKH,gDAEC;AAED,gDAMC;AAbD,yCAAqD;AAGrD,SAAgB,kBAAkB,CAAC,GAAW;IAC5C,OAAO,IAAI,uBAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC;AAC9C,CAAC;AAED,SAAgB,kBAAkB,CAAC,UAAsB;IACvD,IAAI,UAAU,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACrC,OAAQ,UAAU,CAAC,QAAoC,CAAC,OAAO,CAAC,CAAC;IACnE,CAAC;IAED,OAAO,IAAI,uBAAW,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,IAAI,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC;AACrE,CAAC"}
+21
View File
@@ -0,0 +1,21 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Path, PathFragment } from '../path';
import { FileBuffer, FileBufferLike, Host, Stats } from './interface';
export interface SyncHostHandler<StatsT extends object = {}> {
read(path: Path): FileBuffer;
list(path: Path): PathFragment[];
exists(path: Path): boolean;
isDirectory(path: Path): boolean;
isFile(path: Path): boolean;
stat(path: Path): Stats<StatsT> | null;
write(path: Path, content: FileBufferLike): void;
delete(path: Path): void;
rename(from: Path, to: Path): void;
}
export declare function createSyncHost<StatsT extends object = {}>(handler: SyncHostHandler<StatsT>): Host<StatsT>;
+55
View File
@@ -0,0 +1,55 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSyncHost = createSyncHost;
const rxjs_1 = require("rxjs");
function wrapAction(action) {
return new rxjs_1.Observable((subscriber) => {
subscriber.next(action());
subscriber.complete();
});
}
function createSyncHost(handler) {
return new (class {
get capabilities() {
return { synchronous: true };
}
read(path) {
return wrapAction(() => handler.read(path));
}
list(path) {
return wrapAction(() => handler.list(path));
}
exists(path) {
return wrapAction(() => handler.exists(path));
}
isDirectory(path) {
return wrapAction(() => handler.isDirectory(path));
}
isFile(path) {
return wrapAction(() => handler.isFile(path));
}
stat(path) {
return wrapAction(() => handler.stat(path));
}
write(path, content) {
return wrapAction(() => handler.write(path, content));
}
delete(path) {
return wrapAction(() => handler.delete(path));
}
rename(from, to) {
return wrapAction(() => handler.rename(from, to));
}
watch() {
return null;
}
})();
}
//# sourceMappingURL=create.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"create.js","sourceRoot":"","sources":["create.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;AA4BH,wCAgDC;AA1ED,+BAAkC;AAmBlC,SAAS,UAAU,CAAI,MAAe;IACpC,OAAO,IAAI,iBAAU,CAAC,CAAC,UAAU,EAAE,EAAE;QACnC,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;QAC1B,UAAU,CAAC,QAAQ,EAAE,CAAC;IACxB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAgB,cAAc,CAC5B,OAAgC;IAEhC,OAAO,IAAI,CAAC;QACV,IAAI,YAAY;YACd,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC;QAC/B,CAAC;QAED,IAAI,CAAC,IAAU;YACb,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QAC9C,CAAC;QAED,IAAI,CAAC,IAAU;YACb,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QAC9C,CAAC;QAED,MAAM,CAAC,IAAU;YACf,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAChD,CAAC;QAED,WAAW,CAAC,IAAU;YACpB,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;QACrD,CAAC;QAED,MAAM,CAAC,IAAU;YACf,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAChD,CAAC;QAED,IAAI,CAAC,IAAU;YACb,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QAC9C,CAAC;QAED,KAAK,CAAC,IAAU,EAAE,OAAuB;YACvC,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;QACxD,CAAC;QAED,MAAM,CAAC,IAAU;YACf,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAChD,CAAC;QAED,MAAM,CAAC,IAAU,EAAE,EAAQ;YACzB,OAAO,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC;QACpD,CAAC;QAED,KAAK;YACH,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC,EAAE,CAAC;AACP,CAAC"}
+19
View File
@@ -0,0 +1,19 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Observable } from 'rxjs';
import { Path, PathFragment } from '../path';
import { FileBuffer, HostCapabilities, ReadonlyHost, Stats } from './interface';
export declare class Empty implements ReadonlyHost {
readonly capabilities: HostCapabilities;
read(path: Path): Observable<FileBuffer>;
list(path: Path): Observable<PathFragment[]>;
exists(path: Path): Observable<boolean>;
isDirectory(path: Path): Observable<boolean>;
isFile(path: Path): Observable<boolean>;
stat(path: Path): Observable<Stats<{}> | null>;
}
+38
View File
@@ -0,0 +1,38 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Empty = void 0;
const rxjs_1 = require("rxjs");
const exception_1 = require("../../exception");
class Empty {
capabilities = {
synchronous: true,
};
read(path) {
return (0, rxjs_1.throwError)(new exception_1.FileDoesNotExistException(path));
}
list(path) {
return (0, rxjs_1.of)([]);
}
exists(path) {
return (0, rxjs_1.of)(false);
}
isDirectory(path) {
return (0, rxjs_1.of)(false);
}
isFile(path) {
return (0, rxjs_1.of)(false);
}
stat(path) {
// We support stat() but have no file.
return (0, rxjs_1.of)(null);
}
}
exports.Empty = Empty;
//# sourceMappingURL=empty.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"empty.js","sourceRoot":"","sources":["empty.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,+BAAkD;AAClD,+CAA4D;AAI5D,MAAa,KAAK;IACP,YAAY,GAAqB;QACxC,WAAW,EAAE,IAAI;KAClB,CAAC;IAEF,IAAI,CAAC,IAAU;QACb,OAAO,IAAA,iBAAU,EAAC,IAAI,qCAAyB,CAAC,IAAI,CAAC,CAAC,CAAC;IACzD,CAAC;IAED,IAAI,CAAC,IAAU;QACb,OAAO,IAAA,SAAE,EAAC,EAAE,CAAC,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,IAAU;QACf,OAAO,IAAA,SAAE,EAAC,KAAK,CAAC,CAAC;IACnB,CAAC;IAED,WAAW,CAAC,IAAU;QACpB,OAAO,IAAA,SAAE,EAAC,KAAK,CAAC,CAAC;IACnB,CAAC;IAED,MAAM,CAAC,IAAU;QACf,OAAO,IAAA,SAAE,EAAC,KAAK,CAAC,CAAC;IACnB,CAAC;IAED,IAAI,CAAC,IAAU;QACb,sCAAsC;QACtC,OAAO,IAAA,SAAE,EAAC,IAAI,CAAC,CAAC;IAClB,CAAC;CACF;AA7BD,sBA6BC"}
+21
View File
@@ -0,0 +1,21 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as test from './test';
export * from './alias';
export * from './buffer';
export * from './create';
export * from './empty';
export * from './interface';
export * from './memory';
export * from './pattern';
export * from './record';
export * from './safe';
export * from './scoped';
export * from './sync';
export * from './resolver';
export { test };
+61
View File
@@ -0,0 +1,61 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.test = void 0;
const test = __importStar(require("./test"));
exports.test = test;
__exportStar(require("./alias"), exports);
__exportStar(require("./buffer"), exports);
__exportStar(require("./create"), exports);
__exportStar(require("./empty"), exports);
__exportStar(require("./interface"), exports);
__exportStar(require("./memory"), exports);
__exportStar(require("./pattern"), exports);
__exportStar(require("./record"), exports);
__exportStar(require("./safe"), exports);
__exportStar(require("./scoped"), exports);
__exportStar(require("./sync"), exports);
__exportStar(require("./resolver"), exports);
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,6CAA+B;AActB,oBAAI;AAZb,0CAAwB;AACxB,2CAAyB;AACzB,2CAAyB;AACzB,0CAAwB;AACxB,8CAA4B;AAC5B,2CAAyB;AACzB,4CAA0B;AAC1B,2CAAyB;AACzB,yCAAuB;AACvB,2CAAyB;AACzB,yCAAuB;AACvB,6CAA2B"}
+53
View File
@@ -0,0 +1,53 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Observable } from 'rxjs';
import { Path, PathFragment } from '../path';
export type FileBuffer = ArrayBuffer;
export type FileBufferLike = ArrayBufferLike;
export interface HostWatchOptions {
readonly persistent?: boolean;
readonly recursive?: boolean;
}
export declare enum HostWatchEventType {
Changed = 0,
Created = 1,
Deleted = 2,
Renamed = 3
}
export type Stats<T extends object = {}> = T & {
isFile(): boolean;
isDirectory(): boolean;
readonly size: number;
readonly atime: Date;
readonly mtime: Date;
readonly ctime: Date;
readonly birthtime: Date;
};
export interface HostWatchEvent {
readonly time: Date;
readonly type: HostWatchEventType;
readonly path: Path;
}
export interface HostCapabilities {
synchronous: boolean;
}
export interface ReadonlyHost<StatsT extends object = {}> {
readonly capabilities: HostCapabilities;
read(path: Path): Observable<FileBuffer>;
list(path: Path): Observable<PathFragment[]>;
exists(path: Path): Observable<boolean>;
isDirectory(path: Path): Observable<boolean>;
isFile(path: Path): Observable<boolean>;
stat(path: Path): Observable<Stats<StatsT> | null> | null;
}
export interface Host<StatsT extends object = {}> extends ReadonlyHost<StatsT> {
write(path: Path, content: FileBufferLike): Observable<void>;
delete(path: Path): Observable<void>;
rename(from: Path, to: Path): Observable<void>;
watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> | null;
}
+18
View File
@@ -0,0 +1,18 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.HostWatchEventType = void 0;
var HostWatchEventType;
(function (HostWatchEventType) {
HostWatchEventType[HostWatchEventType["Changed"] = 0] = "Changed";
HostWatchEventType[HostWatchEventType["Created"] = 1] = "Created";
HostWatchEventType[HostWatchEventType["Deleted"] = 2] = "Deleted";
HostWatchEventType[HostWatchEventType["Renamed"] = 3] = "Renamed";
})(HostWatchEventType || (exports.HostWatchEventType = HostWatchEventType = {}));
//# sourceMappingURL=interface.js.map
@@ -0,0 +1 @@
{"version":3,"file":"interface.js","sourceRoot":"","sources":["interface.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAaH,IAAY,kBAKX;AALD,WAAY,kBAAkB;IAC5B,iEAAW,CAAA;IACX,iEAAW,CAAA;IACX,iEAAW,CAAA;IACX,iEAAW,CAAA;AACb,CAAC,EALW,kBAAkB,kCAAlB,kBAAkB,QAK7B"}
+49
View File
@@ -0,0 +1,49 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Observable } from 'rxjs';
import { Path, PathFragment } from '../path';
import { FileBuffer, Host, HostCapabilities, HostWatchEvent, HostWatchEventType, HostWatchOptions, Stats } from './interface';
export interface SimpleMemoryHostStats {
readonly content: FileBuffer | null;
inspect(): string;
}
export declare class SimpleMemoryHost implements Host<{}> {
protected _cache: Map<Path, Stats<SimpleMemoryHostStats>>;
private _watchers;
protected _newDirStats(): Stats<SimpleMemoryHostStats>;
protected _newFileStats(content: FileBuffer, oldStats?: Stats<SimpleMemoryHostStats>): Stats<SimpleMemoryHostStats>;
constructor();
protected _toAbsolute(path: Path): Path;
protected _updateWatchers(path: Path, type: HostWatchEventType): void;
get capabilities(): HostCapabilities;
/**
* List of protected methods that give direct access outside the observables to the cache
* and internal states.
*/
protected _write(path: Path, content: FileBuffer): void;
protected _read(path: Path): FileBuffer;
protected _delete(path: Path): void;
protected _rename(from: Path, to: Path): void;
protected _list(path: Path): PathFragment[];
protected _exists(path: Path): boolean;
protected _isDirectory(path: Path): boolean;
protected _isFile(path: Path): boolean;
protected _stat(path: Path): Stats<SimpleMemoryHostStats> | null;
protected _watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent>;
write(path: Path, content: FileBuffer): Observable<void>;
read(path: Path): Observable<FileBuffer>;
delete(path: Path): Observable<void>;
rename(from: Path, to: Path): Observable<void>;
list(path: Path): Observable<PathFragment[]>;
exists(path: Path): Observable<boolean>;
isDirectory(path: Path): Observable<boolean>;
isFile(path: Path): Observable<boolean>;
stat(path: Path): Observable<Stats<{}> | null> | null;
watch(path: Path, options?: HostWatchOptions): Observable<HostWatchEvent> | null;
reset(): void;
}
+332
View File
@@ -0,0 +1,332 @@
"use strict";
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleMemoryHost = void 0;
const rxjs_1 = require("rxjs");
const exception_1 = require("../../exception");
const path_1 = require("../path");
const interface_1 = require("./interface");
class SimpleMemoryHost {
_cache = new Map();
_watchers = new Map();
_newDirStats() {
return {
inspect() {
return '<Directory>';
},
isFile() {
return false;
},
isDirectory() {
return true;
},
size: 0,
atime: new Date(),
ctime: new Date(),
mtime: new Date(),
birthtime: new Date(),
content: null,
};
}
_newFileStats(content, oldStats) {
return {
inspect() {
return `<File size(${content.byteLength})>`;
},
isFile() {
return true;
},
isDirectory() {
return false;
},
size: content.byteLength,
atime: oldStats ? oldStats.atime : new Date(),
ctime: new Date(),
mtime: new Date(),
birthtime: oldStats ? oldStats.birthtime : new Date(),
content,
};
}
constructor() {
this._cache.set((0, path_1.normalize)('/'), this._newDirStats());
}
_toAbsolute(path) {
return (0, path_1.isAbsolute)(path) ? path : (0, path_1.normalize)('/' + path);
}
_updateWatchers(path, type) {
const time = new Date();
let currentPath = path;
let parent = null;
if (this._watchers.size == 0) {
// Nothing to do if there's no watchers.
return;
}
const maybeWatcher = this._watchers.get(currentPath);
if (maybeWatcher) {
maybeWatcher.forEach((watcher) => {
const [options, subject] = watcher;
subject.next({ path, time, type });
if (!options.persistent && type == interface_1.HostWatchEventType.Deleted) {
subject.complete();
this._watchers.delete(currentPath);
}
});
}
do {
currentPath = parent !== null ? parent : currentPath;
parent = (0, path_1.dirname)(currentPath);
const maybeWatcher = this._watchers.get(currentPath);
if (maybeWatcher) {
maybeWatcher.forEach((watcher) => {
const [options, subject] = watcher;
if (!options.recursive) {
return;
}
subject.next({ path, time, type });
if (!options.persistent && type == interface_1.HostWatchEventType.Deleted) {
subject.complete();
this._watchers.delete(currentPath);
}
});
}
} while (parent != currentPath);
}
get capabilities() {
return { synchronous: true };
}
/**
* List of protected methods that give direct access outside the observables to the cache
* and internal states.
*/
_write(path, content) {
path = this._toAbsolute(path);
const old = this._cache.get(path);
if (old && old.isDirectory()) {
throw new exception_1.PathIsDirectoryException(path);
}
// Update all directories. If we find a file we know it's an invalid write.
const fragments = (0, path_1.split)(path);
let curr = (0, path_1.normalize)('/');
for (const fr of fragments) {
curr = (0, path_1.join)(curr, fr);
const maybeStats = this._cache.get(fr);
if (maybeStats) {
if (maybeStats.isFile()) {
throw new exception_1.PathIsFileException(curr);
}
}
else {
this._cache.set(curr, this._newDirStats());
}
}
// Create the stats.
const stats = this._newFileStats(content, old);
this._cache.set(path, stats);
this._updateWatchers(path, old ? interface_1.HostWatchEventType.Changed : interface_1.HostWatchEventType.Created);
}
_read(path) {
path = this._toAbsolute(path);
const maybeStats = this._cache.get(path);
if (!maybeStats) {
throw new exception_1.FileDoesNotExistException(path);
}
else if (maybeStats.isDirectory()) {
throw new exception_1.PathIsDirectoryException(path);
}
else if (!maybeStats.content) {
throw new exception_1.PathIsDirectoryException(path);
}
else {
return maybeStats.content;
}
}
_delete(path) {
path = this._toAbsolute(path);
if (this._isDirectory(path)) {
for (const [cachePath] of this._cache.entries()) {
if (cachePath.startsWith(path + path_1.NormalizedSep) || cachePath === path) {
this._cache.delete(cachePath);
}
}
}
else {
this._cache.delete(path);
}
this._updateWatchers(path, interface_1.HostWatchEventType.Deleted);
}
_rename(from, to) {
from = this._toAbsolute(from);
to = this._toAbsolute(to);
if (!this._cache.has(from)) {
throw new exception_1.FileDoesNotExistException(from);
}
else if (this._cache.has(to)) {
throw new exception_1.FileAlreadyExistException(to);
}
if (this._isDirectory(from)) {
for (const path of this._cache.keys()) {
if (path.startsWith(from + path_1.NormalizedSep)) {
const content = this._cache.get(path);
if (content) {
// We don't need to clone or extract the content, since we're moving files.
this._cache.set((0, path_1.join)(to, path_1.NormalizedSep, path.slice(from.length)), content);
}
}
}
}
else {
const content = this._cache.get(from);
if (content) {
const fragments = (0, path_1.split)(to);
const newDirectories = [];
let curr = (0, path_1.normalize)('/');
for (const fr of fragments) {
curr = (0, path_1.join)(curr, fr);
const maybeStats = this._cache.get(fr);
if (maybeStats) {
if (maybeStats.isFile()) {
throw new exception_1.PathIsFileException(curr);
}
}
else {
newDirectories.push(curr);
}
}
for (const newDirectory of newDirectories) {
this._cache.set(newDirectory, this._newDirStats());
}
this._cache.delete(from);
this._cache.set(to, content);
}
}
this._updateWatchers(from, interface_1.HostWatchEventType.Renamed);
}
_list(path) {
path = this._toAbsolute(path);
if (this._isFile(path)) {
throw new exception_1.PathIsFileException(path);
}
const fragments = (0, path_1.split)(path);
const result = new Set();
if (path !== path_1.NormalizedRoot) {
for (const p of this._cache.keys()) {
if (p.startsWith(path + path_1.NormalizedSep)) {
result.add((0, path_1.split)(p)[fragments.length]);
}
}
}
else {
for (const p of this._cache.keys()) {
if (p.startsWith(path_1.NormalizedSep) && p !== path_1.NormalizedRoot) {
result.add((0, path_1.split)(p)[1]);
}
}
}
return [...result];
}
_exists(path) {
return !!this._cache.get(this._toAbsolute(path));
}
_isDirectory(path) {
const maybeStats = this._cache.get(this._toAbsolute(path));
return maybeStats ? maybeStats.isDirectory() : false;
}
_isFile(path) {
const maybeStats = this._cache.get(this._toAbsolute(path));
return maybeStats ? maybeStats.isFile() : false;
}
_stat(path) {
const maybeStats = this._cache.get(this._toAbsolute(path));
if (!maybeStats) {
return null;
}
else {
return maybeStats;
}
}
_watch(path, options) {
path = this._toAbsolute(path);
const subject = new rxjs_1.Subject();
let maybeWatcherArray = this._watchers.get(path);
if (!maybeWatcherArray) {
maybeWatcherArray = [];
this._watchers.set(path, maybeWatcherArray);
}
maybeWatcherArray.push([options || {}, subject]);
return subject.asObservable();
}
write(path, content) {
return new rxjs_1.Observable((obs) => {
this._write(path, content);
obs.next();
obs.complete();
});
}
read(path) {
return new rxjs_1.Observable((obs) => {
const content = this._read(path);
obs.next(content);
obs.complete();
});
}
delete(path) {
return new rxjs_1.Observable((obs) => {
this._delete(path);
obs.next();
obs.complete();
});
}
rename(from, to) {
return new rxjs_1.Observable((obs) => {
this._rename(from, to);
obs.next();
obs.complete();
});
}
list(path) {
return new rxjs_1.Observable((obs) => {
obs.next(this._list(path));
obs.complete();
});
}
exists(path) {
return new rxjs_1.Observable((obs) => {
obs.next(this._exists(path));
obs.complete();
});
}
isDirectory(path) {
return new rxjs_1.Observable((obs) => {
obs.next(this._isDirectory(path));
obs.complete();
});
}
isFile(path) {
return new rxjs_1.Observable((obs) => {
obs.next(this._isFile(path));
obs.complete();
});
}
// Some hosts may not support stat.
stat(path) {
return new rxjs_1.Observable((obs) => {
obs.next(this._stat(path));
obs.complete();
});
}
watch(path, options) {
return this._watch(path, options);
}
reset() {
this._cache.clear();
this._watchers.clear();
}
}
exports.SimpleMemoryHost = SimpleMemoryHost;
//# sourceMappingURL=memory.js.map
File diff suppressed because one or more lines are too long
+17
View File
@@ -0,0 +1,17 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import { Path } from '../path';
import { ResolverHost } from './resolver';
export type ReplacementFunction = (path: Path) => Path;
/**
*/
export declare class PatternMatchingHost<StatsT extends object = {}> extends ResolverHost<StatsT> {
protected _patterns: Map<RegExp, ReplacementFunction>;
addPattern(pattern: string | string[], replacementFn: ReplacementFunction): void;
protected _resolve(path: Path): Path;
}

Some files were not shown because too many files have changed in this diff Show More