@sevtech/kit 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -0
- package/fesm2022/http.mjs +1292 -0
- package/fesm2022/http.mjs.map +1 -0
- package/fesm2022/localization.mjs +344 -0
- package/fesm2022/localization.mjs.map +1 -0
- package/fesm2022/misc.mjs +352 -0
- package/fesm2022/misc.mjs.map +1 -0
- package/fesm2022/ng-misc.mjs +132 -0
- package/fesm2022/ng-misc.mjs.map +1 -0
- package/fesm2022/ng-sw.mjs +269 -0
- package/fesm2022/ng-sw.mjs.map +1 -0
- package/fesm2022/sevtech-kit.mjs +6 -0
- package/fesm2022/sevtech-kit.mjs.map +1 -0
- package/fesm2022/sw-scripts.mjs +92 -0
- package/fesm2022/sw-scripts.mjs.map +1 -0
- package/fesm2022/sw-shared.mjs +32 -0
- package/fesm2022/sw-shared.mjs.map +1 -0
- package/fesm2022/ui-yoda.mjs +583 -0
- package/fesm2022/ui-yoda.mjs.map +1 -0
- package/fesm2022/ui.mjs +133 -0
- package/fesm2022/ui.mjs.map +1 -0
- package/http/index.d.ts +977 -0
- package/index.d.ts +2 -0
- package/localization/index.d.ts +89 -0
- package/misc/index.d.ts +509 -0
- package/ng-misc/index.d.ts +199 -0
- package/package.json +94 -0
- package/service-worker/index.d.ts +109 -0
- package/service-worker/scripts/index.d.ts +52 -0
- package/service-worker/shared/index.d.ts +40 -0
- package/ui/index.d.ts +46 -0
- package/ui/yoda/index.d.ts +186 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"localization.mjs","sources":["../../../projects/kit/localization/lib/pipes/locale-date.pipe.ts","../../../projects/kit/localization/lib/pipes/locale-percent.pipe.ts","../../../projects/kit/localization/lib/pipes/locale-decimal.pipe.ts","../../../projects/kit/localization/lib/pipes/locale-currency.pipe.ts","../../../projects/kit/localization/lib/localization.constant.ts","../../../projects/kit/localization/lib/localization.token.ts","../../../projects/kit/localization/lib/utils.ts","../../../projects/kit/localization/lib/error.ts","../../../projects/kit/localization/lib/localization-config.ts","../../../projects/kit/localization/lib/localization.service.ts","../../../projects/kit/localization/lib/translate-parser.ts","../../../projects/kit/localization/lib/providers.ts","../../../projects/kit/localization/localization.ts"],"sourcesContent":["import type { PipeTransform } from '@angular/core';\r\nimport type { Nil } from '@sevtech/kit/misc';\r\n\r\nimport { Pipe } from '@angular/core';\r\nimport { DatePipe as NativeDatePipe } from '@angular/common';\r\n\r\n@Pipe({\r\n name: 'localeDate',\r\n})\r\nexport class LocaleDatePipe extends NativeDatePipe implements PipeTransform {\r\n override transform(\r\n value: string | number | Date,\r\n locale: string,\r\n format?: string,\r\n timezone?: string,\r\n ): string | null;\r\n override transform(value: Nil, locale: string, format?: string, timezone?: string): null;\r\n override transform(\r\n value: string | number | Nil | Date,\r\n locale: string,\r\n format?: string,\r\n timezone?: string,\r\n ): string | null {\r\n return super.transform(value, format, timezone, locale);\r\n }\r\n}\r\n","import type { PipeTransform } from '@angular/core';\r\nimport type { Nil } from '@sevtech/kit/misc';\r\n\r\nimport { Pipe } from '@angular/core';\r\nimport { PercentPipe as NativePercentPipe } from '@angular/common';\r\n\r\n@Pipe({\r\n name: 'localePercent',\r\n})\r\nexport class LocalePercentPipe extends NativePercentPipe implements PipeTransform {\r\n override transform(value: number | string, locale: string, digitsInfo?: string): string | null;\r\n override transform(value: Nil, locale: string, digitsInfo?: string): null;\r\n override transform(\r\n value: number | string | Nil,\r\n locale: string,\r\n digitsInfo?: string,\r\n ): string | null {\r\n return super.transform(value, digitsInfo, locale);\r\n }\r\n}\r\n","import type { PipeTransform } from '@angular/core';\r\nimport type { Nil } from '@sevtech/kit/misc';\r\n\r\nimport { Pipe } from '@angular/core';\r\nimport { DecimalPipe as NativeDecimalPipe } from '@angular/common';\r\n\r\n@Pipe({\r\n name: 'localeDecimal',\r\n})\r\nexport class LocaleDecimalPipe extends NativeDecimalPipe implements PipeTransform {\r\n override transform(value: number | string, locale: string, digitsInfo?: string): string | null;\r\n override transform(value: null | undefined, locale: string, digitsInfo?: string): null;\r\n override transform(\r\n value: number | string | Nil,\r\n locale: string,\r\n digitsInfo?: string,\r\n ): string | null {\r\n return super.transform(value, digitsInfo, locale);\r\n }\r\n}\r\n","import type { PipeTransform } from '@angular/core';\r\nimport type { Nil } from '@sevtech/kit/misc';\r\n\r\nimport { Pipe, inject, DEFAULT_CURRENCY_CODE } from '@angular/core';\r\nimport { CurrencyPipe as NativeCurrencyPipe } from '@angular/common';\r\n\r\ntype CurrencyDisplay = boolean | 'code' | 'symbol' | 'symbol-narrow' | (string & {});\r\n\r\n@Pipe({\r\n name: 'localCurrency',\r\n})\r\nexport class LocaleCurrencyPipe extends NativeCurrencyPipe implements PipeTransform {\r\n private readonly defaultCurrencyCode = inject(DEFAULT_CURRENCY_CODE, { optional: true }) ?? 'USD';\r\n\r\n override transform(\r\n value: number | string,\r\n locale: string,\r\n code?: string,\r\n display?: CurrencyDisplay,\r\n digitsInfo?: string,\r\n ): string | null;\r\n override transform(\r\n value: Nil,\r\n locale: string,\r\n code?: string,\r\n display?: CurrencyDisplay,\r\n digitsInfo?: string,\r\n ): null;\r\n override transform(\r\n value: number | string | Nil,\r\n locale: string,\r\n currencyCode: string = this.defaultCurrencyCode,\r\n display: CurrencyDisplay = 'symbol',\r\n digitsInfo?: string,\r\n ): string | null {\r\n return super.transform(value, currencyCode, display, digitsInfo, locale);\r\n }\r\n}\r\n","import type { ProviderConfig } from './localization.type';\r\n\r\nexport const START_WEEK = 0;\r\nexport const END_WEEK = 6;\r\nexport const LOCALE = 'ru' as const;\r\n\r\nexport const DEFAULT_CONFIG = {\r\n available: {},\r\n suffix: '.json',\r\n prefix: './i18n/',\r\n} as const satisfies ProviderConfig;\r\n","import type { Observable } from 'rxjs';\nimport type { Nil } from '@sevtech/kit/misc';\nimport type { MaybeAsync } from '@sevtech/kit/ng-misc';\nimport type { AvailableLocales } from './localization.type';\n\nimport { of } from 'rxjs';\nimport { InjectionToken } from '@angular/core';\nimport { LOCALE, START_WEEK } from './localization.constant';\n\nexport const LOCALE_SYNC = new InjectionToken<(locale: string) => Promise<void> | void>(\n '[LOCALE_SYNC]: предоставляет функцию, для синхронизации текущей активной локали',\n);\n\nexport const WEEK_START = new InjectionToken<MaybeAsync<number>>(\n '[WEEK_START]: предоставляет числовое представление (от 0 до 6) первого дня недели для активной локали',\n {\n providedIn: 'root',\n factory: () => of(START_WEEK),\n },\n);\n\nexport const LOCALE_START = new InjectionToken<Observable<string | Nil>>(\n '[LOCALE_START]: предоставляет стартовую локаль приложения',\n {\n providedIn: 'root',\n factory: () => of(LOCALE),\n },\n);\n\nexport const DEFAULT_LOCALE = new InjectionToken<string>(\n '[DEFAULT_LOCALE]: предоставляет локаль приложения по умолчанию',\n {\n providedIn: 'root',\n factory: () => LOCALE,\n },\n);\n\nexport const AVAILABLE_LOCALES = new InjectionToken<Map<string, AvailableLocales[string]>>(\n '[AVAILABLE_LOCALES]: предоставляет доступные локали в приложении',\n {\n providedIn: 'root',\n factory: () =>\n new Map<string, AvailableLocales[string]>([\n [LOCALE, async () => (await import(`@angular/common/locales/ru`)).default],\n ]),\n },\n);\n","import type { WeekDay, ProviderConfig, AvailableLocales } from './localization.type';\r\n\r\nimport { isNumber, isPlainObject } from '@sevtech/kit/misc';\r\nimport { END_WEEK, START_WEEK, DEFAULT_CONFIG } from './localization.constant';\r\n\r\nexport function isWeekDay(data: unknown): data is WeekDay {\r\n return isNumber(data) && data >= START_WEEK && data <= END_WEEK;\r\n}\r\n\r\nexport function isProviderConfig(data: unknown): data is ProviderConfig {\r\n return isPlainObject(data) && 'available' in data && 'suffix' in data && 'prefix' in data;\r\n}\r\n\r\nexport function normalizeProviderConfig(data: ProviderConfig | AvailableLocales): ProviderConfig {\r\n const config = isProviderConfig(data) ? data : { available: data };\r\n\r\n return {\r\n ...DEFAULT_CONFIG,\r\n ...config,\r\n };\r\n}\r\n","export class LocalizationError extends Error {\r\n override readonly name = LocalizationError.name;\r\n payload: unknown;\r\n\r\n constructor(message: string, payload?: unknown, cause?: unknown) {\r\n super(message, { cause });\r\n this.payload = payload;\r\n }\r\n}\r\n","import type { Nil } from '@sevtech/kit/misc';\r\nimport type { ExtractAsync } from '@sevtech/kit/ng-misc'\r\nimport type { LocaleItem } from './localization.type';\r\n\r\nimport { inject, signal, Injectable, DOCUMENT } from '@angular/core';\r\nimport { registerLocaleData } from '@angular/common';\r\nimport { takeUntilDestroyed } from '@angular/core/rxjs-interop';\r\nimport { map, merge, Subject, switchMap, firstValueFrom, distinctUntilChanged } from 'rxjs';\r\nimport { TranslateService } from '@ngx-translate/core';\r\nimport { LOCALE_SYNC, LOCALE_START, DEFAULT_LOCALE, AVAILABLE_LOCALES } from './localization.token';\r\nimport { LocalizationError } from './error';\r\nimport { isNil, isFunction } from '@sevtech/kit/misc';\r\n\r\n@Injectable({\r\n providedIn: 'root',\r\n})\r\nexport class LocalizationConfig {\r\n private readonly document = inject(DOCUMENT);\r\n private readonly localeStart$ = inject(LOCALE_START);\r\n private readonly translateService = inject(TranslateService);\r\n private readonly availableLocales = inject(AVAILABLE_LOCALES);\r\n private readonly localeSync = inject(LOCALE_SYNC, { optional: true });\r\n\r\n readonly locales = [...this.availableLocales.keys()];\r\n readonly loadedLocales: string[] = [];\r\n readonly defaultLocale = this.getDefaultLocale(inject(DEFAULT_LOCALE));\r\n\r\n private readonly localeSubject = new Subject<string>();\r\n\r\n readonly syncedLocale$ = merge(this.localeSubject.asObservable(), this.localeStart$)\r\n .pipe(\r\n map(locale => this.normalizeLocale(locale)),\r\n distinctUntilChanged(),\r\n );\r\n\r\n readonly locale$$ = signal<string>(this.defaultLocale);\r\n\r\n constructor() {\r\n this.translateService.addLangs(this.locales);\r\n\r\n this.syncedLocale$\r\n .pipe(\r\n switchMap(this.updateLocale.bind(this)),\r\n takeUntilDestroyed()\r\n )\r\n .subscribe();\r\n }\r\n\r\n setLocale(locale: string): void {\r\n this.localeSubject.next(locale);\r\n }\r\n\r\n hasLocale(locale: string): boolean {\r\n return this.availableLocales.has(locale);\r\n }\r\n\r\n async registerLocale(locale: string): Promise<string> {\r\n if (this.loadedLocales.includes(locale)) {\r\n return locale;\r\n }\r\n\r\n const config = this.availableLocales.get(locale);\r\n\r\n if (isNil(config)) {\r\n throw new LocalizationError('Locale is not available', locale);\r\n }\r\n\r\n const { core, extra } = await this.loadLocaleConfig(config);\r\n\r\n registerLocaleData(core, locale, extra);\r\n this.loadedLocales.push(locale);\r\n\r\n return locale;\r\n }\r\n\r\n private getDefaultLocale(locale: string): string {\r\n return this.availableLocales.has(locale)\r\n ? locale\r\n : this.locales[0];\r\n }\r\n\r\n private normalizeLocale(locale: string | Nil): string {\r\n return locale && this.availableLocales.has(locale)\r\n ? locale\r\n : this.defaultLocale;\r\n }\r\n\r\n private changeDocumentLocale(locale: string): void {\r\n if (isNil(this.document.documentElement)) {\r\n return;\r\n }\r\n\r\n this.document.documentElement.lang = locale;\r\n }\r\n\r\n private async updateLocale(locale: string): Promise<void> {\r\n await this.registerLocale(locale);\r\n await firstValueFrom(this.translateService.use(locale));\r\n\r\n this.changeDocumentLocale(locale);\r\n\r\n if (isFunction(this.localeSync)) {\r\n await this.localeSync(locale);\r\n }\r\n\r\n this.locale$$.set(locale);\r\n }\r\n\r\n private async loadLocaleConfig(config: LocaleItem | LocaleItem['core']): Promise<{\r\n core: ExtractAsync<ReturnType<LocaleItem['core']>>\r\n extra?: ExtractAsync<ReturnType<LocaleItem['extra']>>\r\n }> {\r\n if (isFunction(config)) {\r\n return { core: await config() };\r\n }\r\n\r\n const [core, extra] = await Promise.all([config.core(), config.extra()]);\r\n\r\n return { core, extra };\r\n }\r\n}\r\n","import type { Observable } from 'rxjs';\nimport type { MaybeAsync } from '@sevtech/kit/ng-misc';\nimport type { WeekDay } from './localization.type';\n\nimport { inject, Injectable } from '@angular/core';\nimport { toSignal } from '@angular/core/rxjs-interop';\nimport { from, filter, isObservable, distinctUntilChanged } from 'rxjs';\nimport { WEEK_START } from './localization.token';\nimport { isWeekDay } from './utils';\nimport { START_WEEK } from './localization.constant';\nimport { LocalizationError } from './error';\nimport { LocalizationConfig } from './localization-config';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class LocalizationService {\n private readonly weekStart$ = inject(WEEK_START);\n private readonly localizationConfig = inject(LocalizationConfig);\n\n readonly locales = this.localizationConfig.locales;\n\n readonly weekStart$$ = toSignal(this.normalizeWeekStart(this.weekStart$), {\n initialValue: START_WEEK,\n });\n\n readonly locale$$ = this.localizationConfig.locale$$.asReadonly();\n\n setLocale(locale: string): void {\n if (!this.localizationConfig.hasLocale(locale)) {\n throw new LocalizationError('Locale is not available', locale);\n }\n\n this.localizationConfig.setLocale(locale);\n }\n\n private normalizeWeekStart(value: MaybeAsync<number>): Observable<WeekDay> {\n const weekStart$ = isObservable(value) ? value : from(Promise.resolve(value));\n\n return weekStart$.pipe(filter(isWeekDay), distinctUntilChanged());\n }\n}\n","import type { InterpolateFunction, InterpolationParameters } from '@ngx-translate/core';\r\nimport type { Nil } from '@sevtech/kit/misc';\r\n\r\nimport { getValue, TranslateParser as TranslateParserCommon } from '@ngx-translate/core';\r\nimport { isNumber, isString, isBoolean, isFunction } from '@sevtech/kit/misc';\r\n\r\ntype GetValueFunction = (target: unknown, key: string) => string | Nil;\r\n\r\nconst TEMPLATE_REGEX = /{{\\s?([^{}\\s]*)\\s?}}/g;\r\n\r\nexport class TranslateParser extends TranslateParserCommon {\r\n private readonly getValue = getValue as GetValueFunction;\r\n\r\n interpolate(\r\n expression: string | InterpolateFunction,\r\n parameters?: InterpolationParameters,\r\n ): string | undefined {\r\n if (isNumber(expression) || isBoolean(expression)) {\r\n return expression.toString();\r\n }\r\n\r\n if (isString(expression)) {\r\n return this.interpolateString(expression, parameters);\r\n }\r\n\r\n if (isFunction(expression)) {\r\n return this.interpolateFunction(expression, parameters);\r\n }\r\n\r\n return undefined;\r\n }\r\n\r\n private interpolateFunction(\r\n handler: InterpolateFunction,\r\n parameters?: InterpolationParameters,\r\n ): string {\r\n return handler(parameters);\r\n }\r\n\r\n private interpolateString(expression: string, parameters?: InterpolationParameters): string {\r\n if (!parameters) {\r\n return expression;\r\n }\r\n\r\n return expression.replaceAll(\r\n TEMPLATE_REGEX,\r\n (substring: string, group: string) => this.getValue(parameters, group) ?? substring,\r\n );\r\n }\r\n}\r\n","import type { Provider, EnvironmentProviders } from '@angular/core';\nimport type { Observable } from 'rxjs';\nimport type { Nil } from '@sevtech/kit/misc';\nimport type { MaybeAsync } from '@sevtech/kit/ng-misc';\nimport type { ProviderConfig, AvailableLocales } from './localization.type';\n\nimport { inject, LOCALE_ID, provideAppInitializer, makeEnvironmentProviders } from '@angular/core';\nimport { of } from 'rxjs';\nimport { provideTranslateHttpLoader } from '@ngx-translate/http-loader';\nimport {\n TranslateService,\n provideTranslateService,\n TranslateParser as NgxTranslateParser,\n} from '@ngx-translate/core';\nimport { TranslateParser } from './translate-parser';\nimport { LocalizationError } from './error';\nimport { LocalizationService } from './localization.service';\nimport { LocalizationConfig } from './localization-config';\nimport { isFunction, isPlainObject } from '@sevtech/kit/misc';\nimport { normalizeProviderConfig } from './utils';\nimport {\n WEEK_START,\n LOCALE_SYNC,\n LOCALE_START,\n DEFAULT_LOCALE,\n AVAILABLE_LOCALES,\n} from './localization.token';\n\nconst enum Feature {\n weekStart = 3,\n localeSync = 0,\n localeStart = 1,\n defaultLocale = 2,\n}\n\ntype i18nProvider<Brand extends Feature> = Provider & { __brand: Brand };\n\ntype i18nProviders =\n | ReturnType<typeof withWeekStart>\n | ReturnType<typeof withLocaleSync>\n | ReturnType<typeof withLocaleStart>\n | ReturnType<typeof withDefaultLocale>;\n\nfunction brandProvider<T extends Feature>(provider: Provider): i18nProvider<T> {\n assertBrandProvider<T>(provider);\n return provider;\n}\n\nfunction assertBrandProvider<T extends Feature>(data: unknown): asserts data is i18nProvider<T> {\n if (!data) {\n throw new LocalizationError('Invalid FeatureProvider');\n }\n}\n\nasync function appInitializerFactory(): Promise<void> {\n const translateService = inject(TranslateService);\n const localizationConfig = inject(LocalizationConfig);\n\n const defaultLocale = await localizationConfig.registerLocale(localizationConfig.defaultLocale);\n translateService.setFallbackLang(defaultLocale);\n}\n\nfunction getAvailableLocales(locales: AvailableLocales): Map<string, AvailableLocales[string]> {\n const localesMap = new Map<string, AvailableLocales[string]>();\n\n if (!isPlainObject(locales)) {\n throw new LocalizationError(\n 'Invalid Available locales config — expected plain object of locale definitions',\n );\n }\n\n for (const locale in locales) {\n if (locale in locales) {\n localesMap.set(locale, locales[locale]);\n }\n }\n\n return localesMap;\n}\n\nexport function withLocaleStart(locale: string): i18nProvider<Feature.localeStart>;\nexport function withLocaleStart(\n factory: () => Observable<string | Nil>,\n): i18nProvider<Feature.localeStart>;\nexport function withLocaleStart(\n data: string | (() => Observable<string | Nil>),\n): i18nProvider<Feature.localeStart> {\n const factory = isFunction(data) ? data : () => of(data);\n\n return brandProvider({\n provide: LOCALE_START,\n useFactory: factory,\n });\n}\n\nexport function withDefaultLocale(locale: string): i18nProvider<Feature.defaultLocale> {\n return brandProvider({\n provide: DEFAULT_LOCALE,\n useValue: locale,\n });\n}\n\nexport function withWeekStart(factory: () => MaybeAsync<number>): i18nProvider<Feature.weekStart> {\n return brandProvider({\n provide: WEEK_START,\n useFactory: factory,\n });\n}\n\nexport function withLocaleSync(\n syncFunction: () => (locale: string) => void,\n): i18nProvider<Feature.localeSync> {\n return brandProvider({\n provide: LOCALE_SYNC,\n useFactory: syncFunction,\n });\n}\n\nexport function provideLocaleKit(\n available: AvailableLocales,\n ...providers: i18nProviders[]\n): EnvironmentProviders;\nexport function provideLocaleKit(\n config: ProviderConfig,\n ...providers: i18nProviders[]\n): EnvironmentProviders;\nexport function provideLocaleKit(\n data: ProviderConfig | AvailableLocales,\n ...providers: i18nProviders[]\n): EnvironmentProviders {\n const config = normalizeProviderConfig(data);\n\n return makeEnvironmentProviders([\n {\n provide: AVAILABLE_LOCALES,\n useValue: getAvailableLocales(config.available),\n },\n provideTranslateService({\n parser: {\n provide: NgxTranslateParser,\n useClass: TranslateParser,\n },\n loader: provideTranslateHttpLoader({\n prefix: config.prefix,\n suffix: config.suffix,\n }),\n }),\n ...providers,\n {\n provide: LOCALE_ID,\n deps: [LocalizationService],\n useFactory: (service: LocalizationService) => service.locale$$(),\n },\n provideAppInitializer(appInitializerFactory),\n ]);\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["NativeDatePipe","NativePercentPipe","NativeDecimalPipe","NativeCurrencyPipe","TranslateParserCommon","NgxTranslateParser"],"mappings":";;;;;;;;;AASM,MAAO,cAAe,SAAQA,QAAc,CAAA;AAQvC,IAAA,SAAS,CAChB,KAAmC,EACnC,MAAc,EACd,MAAe,EACf,QAAiB,EAAA;AAEjB,QAAA,OAAO,KAAK,CAAC,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC;IACzD;+GAfW,cAAc,EAAA,IAAA,EAAA,IAAA,EAAA,MAAA,EAAA,EAAA,CAAA,eAAA,CAAA,IAAA,EAAA,CAAA,CAAA;6GAAd,cAAc,EAAA,YAAA,EAAA,IAAA,EAAA,IAAA,EAAA,YAAA,EAAA,CAAA,CAAA;;4FAAd,cAAc,EAAA,UAAA,EAAA,CAAA;kBAH1B,IAAI;AAAC,YAAA,IAAA,EAAA,CAAA;AACJ,oBAAA,IAAI,EAAE,YAAY;AACnB,iBAAA;;;ACCK,MAAO,iBAAkB,SAAQC,WAAiB,CAAA;AAG7C,IAAA,SAAS,CAChB,KAA4B,EAC5B,MAAc,EACd,UAAmB,EAAA;QAEnB,OAAO,KAAK,CAAC,SAAS,CAAC,KAAK,EAAE,UAAU,EAAE,MAAM,CAAC;IACnD;+GATW,iBAAiB,EAAA,IAAA,EAAA,IAAA,EAAA,MAAA,EAAA,EAAA,CAAA,eAAA,CAAA,IAAA,EAAA,CAAA,CAAA;6GAAjB,iBAAiB,EAAA,YAAA,EAAA,IAAA,EAAA,IAAA,EAAA,e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A;AACE,YAAA,OAAO,EAAE,iBAAiB;AAC1B,YAAA,QAAQ,EAAE,mBAAmB,CAAC,MAAM,CAAC,SAAS,CAAC;AAChD,SAAA;AACD,QAAA,uBAAuB,CAAC;AACtB,YAAA,MAAM,EAAE;AACN,gBAAA,OAAO,EAAEC,iBAAkB;AAC3B,gBAAA,QAAQ,EAAE,eAAe;AAC1B,aAAA;YACD,MAAM,EAAE,0BAA0B,CAAC;gBACjC,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,MAAM,EAAE,MAAM,CAAC,MAAM;aACtB,CAAC;SACH,CAAC;AACF,QAAA,GAAG,SAAS;AACZ,QAAA;AACE,YAAA,OAAO,EAAE,SAAS;YAClB,IAAI,EAAE,CAAC,mBAAmB,CAAC;YAC3B,UAAU,EAAE,CAAC,OAA4B,KAAK,OAAO,CAAC,QAAQ,EAAE;AACjE,SAAA;QACD,qBAAqB,CAAC,qBAAqB,CAAC;AAC7C,KAAA,CAAC;AACJ;;AC3JA;;AAEG;;;;"}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Генерирует UUID 4 версии
|
|
3
|
+
* @example
|
|
4
|
+
* const id = randomUUID(); // 'f47ac10b-58cc-4372-a567-0e02b2c3d479'
|
|
5
|
+
*/
|
|
6
|
+
function randomUUID() {
|
|
7
|
+
if (crypto && crypto instanceof Crypto) {
|
|
8
|
+
return crypto.randomUUID();
|
|
9
|
+
}
|
|
10
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
|
11
|
+
const r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
|
|
12
|
+
return v.toString(16);
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Проверяет, является ли значение массивом (включая readonly массивы)
|
|
18
|
+
* @example
|
|
19
|
+
* const arr = [1, 2, 3];
|
|
20
|
+
* if (isArray(arr)) {
|
|
21
|
+
* // arr is number[]
|
|
22
|
+
* }
|
|
23
|
+
*/
|
|
24
|
+
function isArray(data) {
|
|
25
|
+
return Array.isArray(data);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Проверяет, является ли значение пустым массивом
|
|
29
|
+
* @example
|
|
30
|
+
* const arr: unknown = [];
|
|
31
|
+
* if (isEmptyArray(arr)) {
|
|
32
|
+
* // arr is unknown[]
|
|
33
|
+
* }
|
|
34
|
+
*/
|
|
35
|
+
function isEmptyArray(data) {
|
|
36
|
+
return Array.isArray(data) && data.length === 0;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Проверяет, является ли значение непустым массивом
|
|
40
|
+
* @example
|
|
41
|
+
* const arr: unknown = [1, 2, 3];
|
|
42
|
+
* if (isNonEmptyArray<number>(arr)) {
|
|
43
|
+
* // arr is number[] и доступен arr[0]
|
|
44
|
+
* }
|
|
45
|
+
*/
|
|
46
|
+
function isNonEmptyArray(data) {
|
|
47
|
+
return Array.isArray(data) && data.length > 0;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Проверяет, является ли значение простым объектом (не массивом, не классом)
|
|
51
|
+
* @example
|
|
52
|
+
* const obj = { key: 'value' };
|
|
53
|
+
* if (isPlainObject(obj)) {
|
|
54
|
+
* // obj is plain object
|
|
55
|
+
* }
|
|
56
|
+
*/
|
|
57
|
+
//@ts-expect-error TS не может привести T к PlainObject<T>, но это верно по конструкции
|
|
58
|
+
function isPlainObject(data) {
|
|
59
|
+
return toBoolean(data) && data?.constructor?.name === 'Object';
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Проверяет, является ли значение функцией
|
|
63
|
+
* @example
|
|
64
|
+
* const fn = () => console.log('test');
|
|
65
|
+
* if (isFunction(fn)) {
|
|
66
|
+
* // fn is Function
|
|
67
|
+
* }
|
|
68
|
+
*/
|
|
69
|
+
function isFunction(data) {
|
|
70
|
+
return typeof data === 'function';
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Проверяет принадлежность значения к определенному классу
|
|
74
|
+
* @example
|
|
75
|
+
* class MyClass {}
|
|
76
|
+
* const instance = new MyClass();
|
|
77
|
+
* if (isInstance(instance, MyClass)) {
|
|
78
|
+
* // instance is MyClass
|
|
79
|
+
* }
|
|
80
|
+
*/
|
|
81
|
+
function isInstance(target, constructor) {
|
|
82
|
+
return target instanceof constructor;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Проверяет, является ли значение объектом Window
|
|
86
|
+
* @example
|
|
87
|
+
* if (isWindow(document)) {
|
|
88
|
+
* // document is Window
|
|
89
|
+
* }
|
|
90
|
+
*/
|
|
91
|
+
function isWindow(data) {
|
|
92
|
+
return typeof data === 'object' && data !== null && data.toString() === '[object Window]';
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function isTypeWith(data, validator) {
|
|
96
|
+
return isFunction(validator) ? validator(data) : !!data;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Фабрика для создания кастомных type guard'ов
|
|
100
|
+
* @example
|
|
101
|
+
* const isBoolean = guardFactory<boolean>(data =>
|
|
102
|
+
* typeof data === 'boolean'
|
|
103
|
+
* );
|
|
104
|
+
*
|
|
105
|
+
* if (isBoolean(someValue)) {
|
|
106
|
+
* // someValue is boolean
|
|
107
|
+
* }
|
|
108
|
+
*
|
|
109
|
+
*/
|
|
110
|
+
function guardFactory(fn) {
|
|
111
|
+
return (data) => fn(data);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Проверяет, является ли значение булевым типом
|
|
116
|
+
* @example
|
|
117
|
+
* isBoolean(true) // => true
|
|
118
|
+
* isBoolean('false') // => false
|
|
119
|
+
*/
|
|
120
|
+
const isBoolean = guardFactory(data => typeof data === 'boolean');
|
|
121
|
+
/**
|
|
122
|
+
* Проверяет, является ли значение числом (исключает массивы и NaN)
|
|
123
|
+
* @example
|
|
124
|
+
* isNumber(42) // => true
|
|
125
|
+
* isNumber('42') // => true
|
|
126
|
+
* isNumber('42t') // => false
|
|
127
|
+
* isNumber(NaN) // => false
|
|
128
|
+
*/
|
|
129
|
+
const isNumber = guardFactory((data) => !Array.isArray(data) && data - parseFloat(data) + 1 >= 0);
|
|
130
|
+
/**
|
|
131
|
+
* Проверяет, является ли значение строкой
|
|
132
|
+
* @example
|
|
133
|
+
* isString('hello') // => true
|
|
134
|
+
* isString(123) // => false
|
|
135
|
+
*/
|
|
136
|
+
const isString = guardFactory(data => typeof data === 'string');
|
|
137
|
+
/**
|
|
138
|
+
* Проверяет, является ли значение пустой строкой
|
|
139
|
+
* @example
|
|
140
|
+
* isEmptyString(' ') // => true
|
|
141
|
+
* isEmptyString('') // => true
|
|
142
|
+
* isEmptyString(' test ') // => false
|
|
143
|
+
*/
|
|
144
|
+
const isEmptyString = guardFactory(data => isString(data) && data.trim().length === 0);
|
|
145
|
+
/**
|
|
146
|
+
* Проверяет, является ли значение непустой строкой
|
|
147
|
+
* @example
|
|
148
|
+
* isNonEmptyString('test') // => true
|
|
149
|
+
* isNonEmptyString(' ') // => false
|
|
150
|
+
*/
|
|
151
|
+
const isNonEmptyString = guardFactory(data => isString(data) && data.trim().length > 0);
|
|
152
|
+
/**
|
|
153
|
+
* Проверяет, является ли значение undefined
|
|
154
|
+
* @example
|
|
155
|
+
* isUndefined(undefined) // => true
|
|
156
|
+
* isUndefined(null) // => false
|
|
157
|
+
*/
|
|
158
|
+
const isUndefined = guardFactory(data => data === undefined);
|
|
159
|
+
/**
|
|
160
|
+
* Проверяет, является ли значение null или undefined
|
|
161
|
+
* @example
|
|
162
|
+
* isNil(null) // => true
|
|
163
|
+
* isNil(undefined) // => true
|
|
164
|
+
* isNil(0) // => false
|
|
165
|
+
*/
|
|
166
|
+
const isNil = guardFactory(data => data === null || data === undefined);
|
|
167
|
+
/**
|
|
168
|
+
* Проверяет, что значение определено (не null и не undefined)
|
|
169
|
+
* @example
|
|
170
|
+
* isDefined('test') // => true
|
|
171
|
+
* isDefined(null) // => false
|
|
172
|
+
*/
|
|
173
|
+
function isDefined(data) {
|
|
174
|
+
return isNil(data) === false;
|
|
175
|
+
}
|
|
176
|
+
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
177
|
+
/**
|
|
178
|
+
* Проверяет, что переданное значение является UUID
|
|
179
|
+
* @example
|
|
180
|
+
* isValidUUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') // true
|
|
181
|
+
* isValidUUID('f47ac10b-58cc-4372-a567-0e02b2c3d479') // true
|
|
182
|
+
* isValidUUID('6ba7b810-9eee-e1d1-80b4-00c04fd43') // false
|
|
183
|
+
*/
|
|
184
|
+
const isValidUUID = guardFactory(data => isString(data) && UUID_REGEX.test(data));
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Проверяет HEX-цвета без альфа-канала (3 или 6 символов)
|
|
188
|
+
* @example #f00, #ff0000
|
|
189
|
+
*/
|
|
190
|
+
const isHexWithoutAlpha = guardFactory(data => isString(data) && /^#(?:[a-f\d]{3}|[a-f\d]{6})$/i.test(data));
|
|
191
|
+
/**
|
|
192
|
+
* Проверяет HEX-цвета с альфа-каналом (4 или 8 символов)
|
|
193
|
+
* @example #f00a, #ff0000ff
|
|
194
|
+
*/
|
|
195
|
+
const isHexWithAlpha = guardFactory(data => isString(data) && /^#(?:[a-f\d]{4}|[a-f\d]{8})$/i.test(data));
|
|
196
|
+
/**
|
|
197
|
+
* Проверяет любой валидный HEX-цвет
|
|
198
|
+
* @example #f00, #ff0000, #f00a, #ff0000ff
|
|
199
|
+
*/
|
|
200
|
+
const isHexColor = guardFactory(data => isHexWithoutAlpha(data) || isHexWithAlpha(data));
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Пустая функция-заглушка, возвращающая саму себя
|
|
204
|
+
* @description
|
|
205
|
+
* - Не имеет побочных эффектов
|
|
206
|
+
* - Может использоваться для инициализации или подмены функций
|
|
207
|
+
*
|
|
208
|
+
* @example
|
|
209
|
+
* const callback = noop; // Безопасная заглушка
|
|
210
|
+
* callback(); // Возвращает саму функцию noop
|
|
211
|
+
*/
|
|
212
|
+
const noop = () => noop;
|
|
213
|
+
/**
|
|
214
|
+
* Преобразует значение в boolean по правилам Angular
|
|
215
|
+
* @example
|
|
216
|
+
* toBoolean(null) // false
|
|
217
|
+
* toBoolean('false') // false
|
|
218
|
+
* toBoolean(0) // true
|
|
219
|
+
* toBoolean({}) // true
|
|
220
|
+
*/
|
|
221
|
+
function toBoolean(value) {
|
|
222
|
+
return value !== null && `${value}` !== 'false';
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Генерирует случайное целое число в заданном диапазоне
|
|
226
|
+
* @example
|
|
227
|
+
* randomNumber(1, 5) // 3
|
|
228
|
+
* randomNumber(10, 10) // 10
|
|
229
|
+
*/
|
|
230
|
+
function randomNumber(min, max) {
|
|
231
|
+
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
232
|
+
}
|
|
233
|
+
function randomArrayItem(array) {
|
|
234
|
+
if (!isNonEmptyArray(array))
|
|
235
|
+
return null;
|
|
236
|
+
const index = Math.floor(Math.random() * array.length);
|
|
237
|
+
return array[index];
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Возвращает первое значение не равное null или undefined из списка аргументов
|
|
241
|
+
* @example
|
|
242
|
+
* coalesce(null, undefined, 42) // 42
|
|
243
|
+
* coalesce('', 0, false) // ''
|
|
244
|
+
*/
|
|
245
|
+
function coalesce(...args) {
|
|
246
|
+
return args.find((arg) => !isNil(arg)) || null;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Безопасно вызывает функцию, если она определена
|
|
250
|
+
* @example
|
|
251
|
+
* safeFnCall(console.log, 'test') // выводит 'test'
|
|
252
|
+
* safeFnCall(undefined, 'test') // undefined
|
|
253
|
+
*/
|
|
254
|
+
function safeFnCall(fn, ...args) {
|
|
255
|
+
return isFunction(fn) ? fn(...args) : undefined;
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Преобразует значение или массив значений в массив
|
|
259
|
+
* @example
|
|
260
|
+
* toArray(1) // [1]
|
|
261
|
+
* toArray([1, 2]) // [1, 2]
|
|
262
|
+
*/
|
|
263
|
+
function toArray(value) {
|
|
264
|
+
return isArray(value) ? value : [value];
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Возвращаем значение или вызывает функцию для получения значения
|
|
268
|
+
* @example
|
|
269
|
+
* resolveMaybeFn(42) // 42
|
|
270
|
+
* resolveMaybeFn(() => 42) // 42
|
|
271
|
+
*/
|
|
272
|
+
function resolveMaybeFn(value) {
|
|
273
|
+
return isFunction(value) ? value() : value;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Разбивает файловый путь на структурные компоненты
|
|
278
|
+
* @example
|
|
279
|
+
* splitPath('src/app/components/header.component.ts?param=1#hash')
|
|
280
|
+
* // Returns:
|
|
281
|
+
* // {
|
|
282
|
+
* // dirname: 'src/app/components/',
|
|
283
|
+
* // filename: 'header.component',
|
|
284
|
+
* // extension: '.ts',
|
|
285
|
+
* // params: '?param=1#hash'
|
|
286
|
+
* // }
|
|
287
|
+
*/
|
|
288
|
+
function splitPath(path) {
|
|
289
|
+
const matchRegexp = /(.*\/)?(\..*?|.*?)(\.[^.]*?)?(#.*$|\?.*$|$)/;
|
|
290
|
+
const result = path.replace(/\\/g, '/').match(matchRegexp) || [];
|
|
291
|
+
const [, dirname = '', filename = '', extension = '', params = ''] = result;
|
|
292
|
+
return { dirname, filename, extension, params };
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function parseJSON(json) {
|
|
296
|
+
if (isNil(json)) {
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
return JSON.parse(json);
|
|
300
|
+
}
|
|
301
|
+
function safeParseJSON(json, fallback) {
|
|
302
|
+
if (isNil(json)) {
|
|
303
|
+
return fallback ?? null;
|
|
304
|
+
}
|
|
305
|
+
try {
|
|
306
|
+
return JSON.parse(json);
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
return fallback ?? null;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function objectKeys(object) {
|
|
314
|
+
return Object.keys(object);
|
|
315
|
+
}
|
|
316
|
+
function objectEntries(object) {
|
|
317
|
+
return Object.entries(object);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Безопасно извлекает значение из объекта по пути в виде строки.
|
|
322
|
+
* @example
|
|
323
|
+
* const obj = { a: { b: 42 }, c: 'hello' };
|
|
324
|
+
* pickKey(obj, 'a.b'); // 42
|
|
325
|
+
* pickKey(obj, 'a.x', 'default'); // 'default'
|
|
326
|
+
* pickKey(obj, 'c'); // 'hello'
|
|
327
|
+
*
|
|
328
|
+
* // Использование кастомного разделителя
|
|
329
|
+
* const obj2 = { a: { b: { c: 1 } } };
|
|
330
|
+
* pickKey(obj2, 'a/b/c', undefined, '/'); // 1
|
|
331
|
+
*/
|
|
332
|
+
function pickKey(object, path, fallback = undefined, separator = '.') {
|
|
333
|
+
if (isNil(object) || !isString(path)) {
|
|
334
|
+
return fallback;
|
|
335
|
+
}
|
|
336
|
+
const keys = path.split(separator);
|
|
337
|
+
let current = object;
|
|
338
|
+
for (const key of keys) {
|
|
339
|
+
if (!isPlainObject(current)) {
|
|
340
|
+
return fallback;
|
|
341
|
+
}
|
|
342
|
+
current = current[key];
|
|
343
|
+
}
|
|
344
|
+
return (current === undefined ? fallback : current);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Generated bundle index. Do not edit.
|
|
349
|
+
*/
|
|
350
|
+
|
|
351
|
+
export { coalesce, guardFactory, isArray, isBoolean, isDefined, isEmptyArray, isEmptyString, isFunction, isHexColor, isHexWithAlpha, isHexWithoutAlpha, isInstance, isNil, isNonEmptyArray, isNonEmptyString, isNumber, isPlainObject, isString, isTypeWith, isUndefined, isValidUUID, isWindow, noop, objectEntries, objectKeys, parseJSON, pickKey, randomArrayItem, randomNumber, randomUUID, resolveMaybeFn, safeFnCall, safeParseJSON, splitPath, toArray, toBoolean };
|
|
352
|
+
//# sourceMappingURL=misc.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"misc.mjs","sources":["../../../projects/kit/misc/lib/utils/random-uuid.ts","../../../projects/kit/misc/lib/type-guards/objects.ts","../../../projects/kit/misc/lib/type-guards/base.ts","../../../projects/kit/misc/lib/type-guards/primitives.ts","../../../projects/kit/misc/lib/type-guards/css.ts","../../../projects/kit/misc/lib/utils/primitives.ts","../../../projects/kit/misc/lib/utils/split-path.ts","../../../projects/kit/misc/lib/utils/parse-json.ts","../../../projects/kit/misc/lib/utils/object.ts","../../../projects/kit/misc/lib/utils/pick-key.ts","../../../projects/kit/misc/misc.ts"],"sourcesContent":["import type { UUID } from '../types';\n\n/**\n * Генерирует UUID 4 версии\n * @example\n * const id = randomUUID(); // 'f47ac10b-58cc-4372-a567-0e02b2c3d479'\n */\nexport function randomUUID(): UUID {\n if (crypto && crypto instanceof Crypto) {\n return crypto.randomUUID();\n }\n\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n const r = (Math.random() * 16) | 0,\n v = c == 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n }) as UUID;\n}\n","import type { ConstructorTypeOf, SafeAny } from '../types';\r\nimport { toBoolean } from '../utils';\r\n\r\n/**\r\n * Проверяет, является ли значение массивом (включая readonly массивы)\r\n * @example\r\n * const arr = [1, 2, 3];\r\n * if (isArray(arr)) {\r\n * // arr is number[]\r\n * }\r\n */\r\nexport function isArray<T>(data: unknown): data is T[] | readonly T[] {\r\n return Array.isArray(data);\r\n}\r\n\r\n/**\r\n * Проверяет, является ли значение пустым массивом\r\n * @example\r\n * const arr: unknown = [];\r\n * if (isEmptyArray(arr)) {\r\n * // arr is unknown[]\r\n * }\r\n */\r\nexport function isEmptyArray<T>(data: unknown): data is T[] {\r\n return Array.isArray(data) && data.length === 0;\r\n}\r\n\r\n/**\r\n * Проверяет, является ли значение непустым массивом\r\n * @example\r\n * const arr: unknown = [1, 2, 3];\r\n * if (isNonEmptyArray<number>(arr)) {\r\n * // arr is number[] и доступен arr[0]\r\n * }\r\n */\r\nexport function isNonEmptyArray<T>(data: unknown): data is T[] {\r\n return Array.isArray(data) && data.length > 0;\r\n}\r\n\r\ntype PlainObject<T> =\r\n [unknown] extends [T]\r\n ? Record<PropertyKey, unknown>\r\n : T extends object\r\n ? T extends Iterable<SafeAny> ? never : T\r\n : never;\r\n\r\n/**\r\n * Проверяет, является ли значение простым объектом (не массивом, не классом)\r\n * @example\r\n * const obj = { key: 'value' };\r\n * if (isPlainObject(obj)) {\r\n * // obj is plain object\r\n * }\r\n */\r\n//@ts-expect-error TS не может привести T к PlainObject<T>, но это верно по конструкции\r\nexport function isPlainObject<T>(data: T): data is PlainObject<T> {\r\n return toBoolean(data) && data?.constructor?.name === 'Object';\r\n}\r\n\r\n/**\r\n * Проверяет, является ли значение функцией\r\n * @example\r\n * const fn = () => console.log('test');\r\n * if (isFunction(fn)) {\r\n * // fn is Function\r\n * }\r\n */\r\nexport function isFunction(data: unknown): data is Function {\r\n return typeof data === 'function';\r\n}\r\n\r\n/**\r\n * Проверяет принадлежность значения к определенному классу\r\n * @example\r\n * class MyClass {}\r\n * const instance = new MyClass();\r\n * if (isInstance(instance, MyClass)) {\r\n * // instance is MyClass\r\n * }\r\n */\r\nexport function isInstance<T>(target: unknown, constructor: ConstructorTypeOf<T>): target is T {\r\n return target instanceof constructor;\r\n}\r\n\r\n/**\r\n * Проверяет, является ли значение объектом Window\r\n * @example\r\n * if (isWindow(document)) {\r\n * // document is Window\r\n * }\r\n */\r\nexport function isWindow<T extends Window = Window>(data: unknown): data is T {\r\n return typeof data === 'object' && data !== null && data.toString() === '[object Window]';\r\n}\r\n","import { isFunction } from './objects';\r\n\r\n/**\r\n * Базовый type guard с возможностью кастомизации проверки.\r\n * @example\r\n * if(isTypeWith<MyType>(someValue)) {\r\n * // someValue is MyType\r\n * }\r\n */\r\nexport function isTypeWith<T>(data: unknown): data is T\r\n\r\n/**\r\n * Базовый type guard с кастомной функцией валидации\r\n * @example\r\n * const result = isTypeWith<number>(someValue, (data: unknown) => typeof data === 'number');\r\n */\r\nexport function isTypeWith<T>(data: unknown, validator: (data: unknown) => boolean): data is T\r\nexport function isTypeWith<T>(data: unknown, validator?: (data: unknown) => boolean): data is T {\r\n return isFunction(validator) ? validator(data): !!data;\r\n}\r\n\r\n/**\r\n * Фабрика для создания кастомных type guard'ов\r\n * @example\r\n * const isBoolean = guardFactory<boolean>(data =>\r\n * typeof data === 'boolean'\r\n * );\r\n *\r\n * if (isBoolean(someValue)) {\r\n * // someValue is boolean\r\n * }\r\n *\r\n */\r\nexport function guardFactory<T>(fn: (data: unknown) => boolean) {\r\n return (data: unknown): data is T => fn(data);\r\n}\r\n","import type { Nil, SafeAny, UUID } from '../types';\r\nimport { guardFactory } from './base';\r\n\r\n/**\r\n * Проверяет, является ли значение булевым типом\r\n * @example\r\n * isBoolean(true) // => true\r\n * isBoolean('false') // => false\r\n */\r\nexport const isBoolean =\r\n guardFactory<boolean>(data => typeof data === 'boolean');\r\n\r\n/**\r\n * Проверяет, является ли значение числом (исключает массивы и NaN)\r\n * @example\r\n * isNumber(42) // => true\r\n * isNumber('42') // => true\r\n * isNumber('42t') // => false\r\n * isNumber(NaN) // => false\r\n */\r\nexport const isNumber =\r\n guardFactory<number>((data: SafeAny) => !Array.isArray(data) && data - parseFloat(data) + 1 >= 0);\r\n\r\n/**\r\n * Проверяет, является ли значение строкой\r\n * @example\r\n * isString('hello') // => true\r\n * isString(123) // => false\r\n */\r\nexport const isString =\r\n guardFactory<string>(data => typeof data === 'string');\r\n\r\n/**\r\n * Проверяет, является ли значение пустой строкой\r\n * @example\r\n * isEmptyString(' ') // => true\r\n * isEmptyString('') // => true\r\n * isEmptyString(' test ') // => false\r\n */\r\nexport const isEmptyString =\r\n guardFactory<string>(data => isString(data) && data.trim().length === 0);\r\n\r\n/**\r\n * Проверяет, является ли значение непустой строкой\r\n * @example\r\n * isNonEmptyString('test') // => true\r\n * isNonEmptyString(' ') // => false\r\n */\r\nexport const isNonEmptyString =\r\n guardFactory<string>(data => isString(data) && data.trim().length > 0);\r\n\r\n/**\r\n * Проверяет, является ли значение undefined\r\n * @example\r\n * isUndefined(undefined) // => true\r\n * isUndefined(null) // => false\r\n */\r\nexport const isUndefined =\r\n guardFactory<undefined>(data => data === undefined);\r\n\r\n/**\r\n * Проверяет, является ли значение null или undefined\r\n * @example\r\n * isNil(null) // => true\r\n * isNil(undefined) // => true\r\n * isNil(0) // => false\r\n */\r\nexport const isNil =\r\n guardFactory<Nil>(data => data === null || data === undefined);\r\n\r\n/**\r\n * Проверяет, что значение определено (не null и не undefined)\r\n * @example\r\n * isDefined('test') // => true\r\n * isDefined(null) // => false\r\n */\r\nexport function isDefined<T>(data: T): data is Exclude<T, Nil> {\r\n return isNil(data) === false;\r\n}\r\n\r\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\r\n\r\n/**\r\n * Проверяет, что переданное значение является UUID\r\n * @example\r\n * isValidUUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8') // true\r\n * isValidUUID('f47ac10b-58cc-4372-a567-0e02b2c3d479') // true\r\n * isValidUUID('6ba7b810-9eee-e1d1-80b4-00c04fd43') // false\r\n */\r\nexport const isValidUUID =\r\n guardFactory<UUID>(data => isString(data) && UUID_REGEX.test(data));\r\n","import { isString } from './primitives';\r\nimport type { CSSHexColor } from '../types';\r\nimport { guardFactory } from './base';\r\n\r\n/**\r\n * Проверяет HEX-цвета без альфа-канала (3 или 6 символов)\r\n * @example #f00, #ff0000\r\n */\r\nexport const isHexWithoutAlpha =\r\n guardFactory<CSSHexColor>(data => isString(data) && /^#(?:[a-f\\d]{3}|[a-f\\d]{6})$/i.test(data))\r\n\r\n/**\r\n * Проверяет HEX-цвета с альфа-каналом (4 или 8 символов)\r\n * @example #f00a, #ff0000ff\r\n */\r\nexport const isHexWithAlpha =\r\n guardFactory<CSSHexColor>(data => isString(data) && /^#(?:[a-f\\d]{4}|[a-f\\d]{8})$/i.test(data));\r\n\r\n/**\r\n * Проверяет любой валидный HEX-цвет\r\n * @example #f00, #ff0000, #f00a, #ff0000ff\r\n */\r\nexport const isHexColor =\r\n guardFactory<CSSHexColor>(data => isHexWithoutAlpha(data) || isHexWithAlpha(data));\r\n","import { isNonEmptyArray, isArray, isFunction, isNil } from '../type-guards';\nimport type { MaybeArray, MaybeFunction, SafeAny } from '../types';\n\n/**\n * Пустая функция-заглушка, возвращающая саму себя\n * @description\n * - Не имеет побочных эффектов\n * - Может использоваться для инициализации или подмены функций\n *\n * @example\n * const callback = noop; // Безопасная заглушка\n * callback(); // Возвращает саму функцию noop\n */\nexport const noop: () => typeof noop = () => noop;\n\n/**\n * Преобразует значение в boolean по правилам Angular\n * @example\n * toBoolean(null) // false\n * toBoolean('false') // false\n * toBoolean(0) // true\n * toBoolean({}) // true\n */\nexport function toBoolean(value: unknown): boolean {\n return value !== null && `${value}` !== 'false';\n}\n\n/**\n * Генерирует случайное целое число в заданном диапазоне\n * @example\n * randomNumber(1, 5) // 3\n * randomNumber(10, 10) // 10\n */\nexport function randomNumber(min: number, max: number): number {\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\n/**\n * Возвращает случайный элемент массива или null\n * @example\n * randomArrayItem([1, 2, 3]) // 2\n * randomArrayItem([]) // null\n * randomArrayItem('test') // null\n */\nexport function randomArrayItem<T>(array: T[]): T\nexport function randomArrayItem<T extends Exclude<SafeAny, []>>(item : T): null\nexport function randomArrayItem<T>(array: T[]): T | null {\n if (!isNonEmptyArray(array) ) return null;\n\n const index = Math.floor(Math.random() * array.length);\n return array[index];\n}\n\n/**\n * Возвращает первое значение не равное null или undefined из списка аргументов\n * @example\n * coalesce(null, undefined, 42) // 42\n * coalesce('', 0, false) // ''\n */\nexport function coalesce<Arg>(...args: Arg[]): NonNullable<Arg> | null {\n return args.find((arg) => !isNil(arg)) || null;\n}\n\n/**\n * Безопасно вызывает функцию, если она определена\n * @example\n * safeFnCall(console.log, 'test') // выводит 'test'\n * safeFnCall(undefined, 'test') // undefined\n */\nexport function safeFnCall<Fn extends ((...args: SafeAny[]) => SafeAny)>(\n fn: Fn | undefined,\n ...args: Parameters<Fn>\n): ReturnType<Fn> | undefined {\n return isFunction(fn) ? fn(...args): undefined;\n}\n\n/**\n * Преобразует значение или массив значений в массив\n * @example\n * toArray(1) // [1]\n * toArray([1, 2]) // [1, 2]\n */\nexport function toArray<T>(value: MaybeArray<T>): T[] {\n return isArray(value) ? value : [value];\n}\n\n/**\n * Возвращаем значение или вызывает функцию для получения значения\n * @example\n * resolveMaybeFn(42) // 42\n * resolveMaybeFn(() => 42) // 42\n */\nexport function resolveMaybeFn<T>(value: MaybeFunction<T>): T {\n return isFunction(value) ? value() : value;\n}\n","type SplitPath = Record<'dirname' | 'filename' | 'extension' | 'params', string>;\n\n/**\n * Разбивает файловый путь на структурные компоненты\n * @example\n * splitPath('src/app/components/header.component.ts?param=1#hash')\n * // Returns:\n * // {\n * // dirname: 'src/app/components/',\n * // filename: 'header.component',\n * // extension: '.ts',\n * // params: '?param=1#hash'\n * // }\n */\nexport function splitPath(path: string): SplitPath {\n const matchRegexp = /(.*\\/)?(\\..*?|.*?)(\\.[^.]*?)?(#.*$|\\?.*$|$)/;\n const result = path.replace(/\\\\/g, '/').match(matchRegexp) || [];\n const [, dirname = '', filename = '', extension = '', params = ''] = result;\n\n return { dirname, filename, extension, params };\n}\n","import { isNil } from '../type-guards';\n\n/**\n * Парсит JSON строку с явной типизацией результата\n * @example\n * const data = parseJSON<{ id: number }>('{\"id\": 123}'); // { id: 123 }\n * parseJSON(null) // null\n * parseJSON('d: 123') // SyntaxError\n */\nexport function parseJSON(json: string | null): null;\nexport function parseJSON<ReturnType>(json: string | null): ReturnType | null;\nexport function parseJSON<ReturnType>(json: string | null): ReturnType | null {\n if (isNil(json)) {\n return null;\n }\n return JSON.parse(json);\n}\n\n/**\n * Безопасный парсинг JSON с обработкой ошибок и fallback значением\n * @example\n * safeParseJSON('invalid') // null\n * safeParseJSON('[1,2,3]') // [1,2,3]\n * safeParseJSON('{invalid}', []) // []\n */\nexport function safeParseJSON(json: string | null): null;\nexport function safeParseJSON<ReturnType>(json: string | null): ReturnType | null;\nexport function safeParseJSON<ReturnType, Fallback = null>(\n json: string | null,\n fallback: Fallback,\n): ReturnType | Fallback;\nexport function safeParseJSON<ReturnType, Fallback>(\n json: string | null,\n fallback?: Fallback,\n): ReturnType | Fallback | null {\n if (isNil(json)) {\n return fallback ?? null;\n }\n\n try {\n return JSON.parse(json);\n } catch {\n return fallback ?? null;\n }\n}\n","import type { Nil, SafeAny, Primitive } from '../types';\n\n/**\n * Типизированная обёртка для Object.keys()\n * @example\n * objectKeys({ a: 1, b: 2 }) // ['a', 'b'] с типом ('a' | 'b')[]\n * objectKeys([1, 2, 3]) // ['0', '1', '2'] с типом string[]\n * objectKeys('test') // [] с типом string[]\n * objectKeys(null) // Ошибка типа\n */\nexport function objectKeys<T extends Nil>(object: T): never;\nexport function objectKeys<T extends Primitive | SafeAny[]>(object: T): string[];\nexport function objectKeys<T extends Record<PropertyKey, SafeAny>>(object: T): Array<keyof T>;\nexport function objectKeys(object: object): unknown {\n return Object.keys(object);\n}\n\n/**\n * Типизированная обёртка для Object.entries()\n * @example\n * objectEntries({ a: 1, b: '2' }) // [['a', 1], ['b', '2']] с типом (['a', number] | ['b', string])[]\n * objectEntries([10, 20]) // [['0', 10], ['1', 20]] с типом [string, number][]\n * objectEntries(new Set([1,2])) // [] с типом []\n * objectEntries('test') // [] с типом []\n */\nexport function objectEntries<T extends Nil>(object: T): never;\nexport function objectEntries<T extends Set<SafeAny> | Map<SafeAny, SafeAny> | Primitive>(\n object: T,\n): [];\nexport function objectEntries<T extends SafeAny[]>(object: T): [string, keyof T][];\nexport function objectEntries<T extends Record<Readonly<string>, SafeAny>>(\n object: T,\n): Array<[keyof T, T[keyof T]]>;\nexport function objectEntries<T>(object: Record<string, T> | ArrayLike<T>): [string, T][];\nexport function objectEntries(object: object): unknown {\n return Object.entries(object);\n}\n","import { isNil, isPlainObject, isString } from '../type-guards';\nimport type { DeepKeys, Nil, PickKey, SafeAny } from '../types';\n\n/**\n * Безопасно извлекает значение из объекта по пути в виде строки.\n * @example\n * const obj = { a: { b: 42 }, c: 'hello' };\n * pickKey(obj, 'a.b'); // 42\n * pickKey(obj, 'a.x', 'default'); // 'default'\n * pickKey(obj, 'c'); // 'hello'\n *\n * // Использование кастомного разделителя\n * const obj2 = { a: { b: { c: 1 } } };\n * pickKey(obj2, 'a/b/c', undefined, '/'); // 1\n */\nexport function pickKey<\n Object extends Record<string, SafeAny>,\n Path extends DeepKeys<Object, Separator>,\n Fallback extends unknown = undefined,\n Separator extends string = '.',\n>(\n object: Object | Nil,\n path: Path,\n fallback: Fallback = undefined as Fallback,\n separator: Separator = '.' as Separator,\n): PickKey<Object, Path> extends Object ? Fallback : PickKey<Object, Path> {\n if (isNil(object) || !isString(path)) {\n return fallback as ReturnType<typeof pickKey>;\n }\n\n const keys = path.split(separator);\n let current = object;\n\n for (const key of keys) {\n if (!isPlainObject(current)) {\n return fallback as ReturnType<typeof pickKey>;\n }\n\n current = current[key];\n }\n\n return (current === undefined ? fallback : current) as ReturnType<typeof pickKey>;\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":"AAEA;;;;AAIG;SACa,UAAU,GAAA;AACxB,IAAA,IAAI,MAAM,IAAI,MAAM,YAAY,MAAM,EAAE;AACtC,QAAA,OAAO,MAAM,CAAC,UAAU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eM,SAAU,aAAa,CAC3B,IAAmB,EACnB,QAAmB,EAAA;AAEnB,IAAA,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE;QACf,OAAO,QAAQ,IAAI,IAAI;IACzB;AAEA,IAAA,IAAI;AACF,QAAA,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;IACzB;AAAE,IAAA,MAAM;QACN,OAAO,QAAQ,IAAI,IAAI;IACzB;AACF;;AC/BM,SAAU,UAAU,CAAC,MAAc,EAAA;AACvC,IAAA,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC;AAC5B;AAmBM,SAAU,aAAa,CAAC,MAAc,EAAA;AAC1C,IAAA,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;AAC/B;;ACjCA;;;;;;;;;;;AAWG;AACG,SAAU,OAAO,CAMrB,MAAoB,EACpB,IAAU,EACV,QAAA,GAAqB,SAAqB,EAC1C,SAAA,GAAuB,GAAgB,EAAA;IAEvC,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;AACpC,QAAA,OAAO,QAAsC;IAC/C;IAEA,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC;IAClC,IAAI,OAAO,GAAG,MAAM;AAEpB,IAAA,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE;AACtB,QAAA,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,EAAE;AAC3B,YAAA,OAAO,QAAsC;QAC/C;AAEA,QAAA,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC;IACxB;AAEA,IAAA,QAAQ,OAAO,KAAK,SAAS,GAAG,QAAQ,GAAG,OAAO;AACpD;;AC1CA;;AAEG;;;;"}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { Observable } from 'rxjs';
|
|
2
|
+
import { booleanAttribute, ViewContainerRef, ComponentRef } from '@angular/core';
|
|
3
|
+
import { NgComponentOutlet } from '@angular/common';
|
|
4
|
+
import { FormControl, FormGroup, FormArray, FormRecord } from '@angular/forms';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Создаёт Observable который эмитит при изменении размеров элемента
|
|
8
|
+
* @example
|
|
9
|
+
* resizeObservable(elementRef.nativeElement).subscribe(entries => {
|
|
10
|
+
* console.log(entries[0].contentRect.width);
|
|
11
|
+
* });
|
|
12
|
+
*/
|
|
13
|
+
function resizeObservable(element) {
|
|
14
|
+
return new Observable(subscriber => {
|
|
15
|
+
const resizeObserver = new ResizeObserver(entries => {
|
|
16
|
+
subscriber.next(entries);
|
|
17
|
+
});
|
|
18
|
+
resizeObserver.observe(element);
|
|
19
|
+
return () => {
|
|
20
|
+
resizeObserver.unobserve(element);
|
|
21
|
+
};
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Transform-функция для булевых HTML-атрибутов.
|
|
27
|
+
* В отличие от `booleanAttribute`, возвращает `true | undefined` вместо `boolean`,
|
|
28
|
+
* что позволяет корректно использовать атрибут в шаблоне — атрибут либо присутствует, либо отсутствует.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* class MyComponent {
|
|
32
|
+
* disabled = input(undefined, { transform: htmlBooleanAttribute });
|
|
33
|
+
* // <my-component disabled /> → true
|
|
34
|
+
* // <my-component /> → undefined
|
|
35
|
+
* }
|
|
36
|
+
*/
|
|
37
|
+
function htmlBooleanAttribute(value) {
|
|
38
|
+
return booleanAttribute(value) || undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Проверяет, является ли значение экземпляром FormControl
|
|
43
|
+
* @example
|
|
44
|
+
* const control = new FormControl<string>('');
|
|
45
|
+
* if (isFormControl<string>(control)) {
|
|
46
|
+
* // control is FormControl<string>
|
|
47
|
+
* }
|
|
48
|
+
*/
|
|
49
|
+
function isFormControl(data) {
|
|
50
|
+
return data instanceof FormControl;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Проверяет, является ли значение экземпляром FormGroup
|
|
54
|
+
* @example
|
|
55
|
+
* const group = new FormGroup({ name: new FormControl('') });
|
|
56
|
+
* if (isFormGroup(group)) {
|
|
57
|
+
* // group is FormGroup
|
|
58
|
+
* }
|
|
59
|
+
*/
|
|
60
|
+
function isFormGroup(data) {
|
|
61
|
+
return data instanceof FormGroup;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Проверяет, является ли значение экземпляром FormArray
|
|
65
|
+
* @example
|
|
66
|
+
* const array = new FormArray([new FormControl('')]);
|
|
67
|
+
* if (isFormArray(array)) {
|
|
68
|
+
* // array is FormArray
|
|
69
|
+
* }
|
|
70
|
+
*/
|
|
71
|
+
function isFormArray(data) {
|
|
72
|
+
return data instanceof FormArray;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Проверяет, является ли значение экземпляром FormRecord
|
|
76
|
+
* @example
|
|
77
|
+
* const record = new FormRecord({ field: new FormControl('') });
|
|
78
|
+
* if (isFormRecord(record)) {
|
|
79
|
+
* // record is FormRecord
|
|
80
|
+
* }
|
|
81
|
+
*/
|
|
82
|
+
function isFormRecord(data) {
|
|
83
|
+
return data instanceof FormRecord;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Проверяет, является ли значение экземпляром ViewContainerRef
|
|
87
|
+
* @example
|
|
88
|
+
* class MyComponent {
|
|
89
|
+
* constructor(public vcr: ViewContainerRef) {}
|
|
90
|
+
*
|
|
91
|
+
* checkType() {
|
|
92
|
+
* if (isViewContainer(this.vcr)) {
|
|
93
|
+
* // this.vcr is ViewContainerRef
|
|
94
|
+
* }
|
|
95
|
+
* }
|
|
96
|
+
* }
|
|
97
|
+
*/
|
|
98
|
+
function isViewContainer(data) {
|
|
99
|
+
return data instanceof ViewContainerRef;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Проверяет, является ли значение экземпляром ComponentRef
|
|
103
|
+
* @example
|
|
104
|
+
* const componentRef = this.componentFactory.create(injector);
|
|
105
|
+
* if (isComponentRef<MyComponent>(componentRef)) {
|
|
106
|
+
* // componentRef is ComponentRef<MyComponent>
|
|
107
|
+
* }
|
|
108
|
+
*/
|
|
109
|
+
function isComponentRef(data) {
|
|
110
|
+
return data instanceof ComponentRef;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Проверяет, является ли значение экземпляром NgComponentOutlet
|
|
114
|
+
* @example
|
|
115
|
+
* class HostComponent {
|
|
116
|
+
* checkOutlet(outlet: unknown) {
|
|
117
|
+
* if (isComponentOutlet(outlet)) {
|
|
118
|
+
* // outlet is NgComponentOutlet
|
|
119
|
+
* }
|
|
120
|
+
* }
|
|
121
|
+
* }
|
|
122
|
+
*/
|
|
123
|
+
function isComponentOutlet(data) {
|
|
124
|
+
return data instanceof NgComponentOutlet;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Generated bundle index. Do not edit.
|
|
129
|
+
*/
|
|
130
|
+
|
|
131
|
+
export { htmlBooleanAttribute, isComponentOutlet, isComponentRef, isFormArray, isFormControl, isFormGroup, isFormRecord, isViewContainer, resizeObservable };
|
|
132
|
+
//# sourceMappingURL=ng-misc.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ng-misc.mjs","sources":["../../../projects/kit/ng-misc/lib/resize-observable.ts","../../../projects/kit/ng-misc/lib/transform-inputs.ts","../../../projects/kit/ng-misc/lib/type-guards.ts","../../../projects/kit/ng-misc/ng-misc.ts"],"sourcesContent":["import { Observable } from 'rxjs';\r\n\r\n/**\r\n * Создаёт Observable который эмитит при изменении размеров элемента\r\n * @example\r\n * resizeObservable(elementRef.nativeElement).subscribe(entries => {\r\n * console.log(entries[0].contentRect.width);\r\n * });\r\n */\r\nexport function resizeObservable(element: HTMLElement): Observable<ResizeObserverEntry[]> {\r\n return new Observable(subscriber => {\r\n const resizeObserver = new ResizeObserver(entries => {\r\n subscriber.next(entries);\r\n });\r\n\r\n resizeObserver.observe(element);\r\n\r\n return () => {\r\n resizeObserver.unobserve(element);\r\n }\r\n })\r\n}\r\n","import { booleanAttribute } from '@angular/core';\n\n/**\n * Transform-функция для булевых HTML-атрибутов.\n * В отличие от `booleanAttribute`, возвращает `true | undefined` вместо `boolean`,\n * что позволяет корректно использовать атрибут в шаблоне — атрибут либо присутствует, либо отсутствует.\n *\n * @example\n * class MyComponent {\n * disabled = input(undefined, { transform: htmlBooleanAttribute });\n * // <my-component disabled /> → true\n * // <my-component /> → undefined\n * }\n */\nexport function htmlBooleanAttribute(value: unknown): true | undefined {\n return booleanAttribute(value) || undefined;\n}\n","import { NgComponentOutlet } from '@angular/common';\nimport { ComponentRef, ViewContainerRef } from '@angular/core';\nimport { FormArray, FormControl, FormGroup, FormRecord } from '@angular/forms';\n\n/**\n * Проверяет, является ли значение экземпляром FormControl\n * @example\n * const control = new FormControl<string>('');\n * if (isFormControl<string>(control)) {\n * // control is FormControl<string>\n * }\n */\nexport function isFormControl<T = unknown>(data: unknown): data is FormControl<T> {\n return data instanceof FormControl;\n}\n\n/**\n * Проверяет, является ли значение экземпляром FormGroup\n * @example\n * const group = new FormGroup({ name: new FormControl('') });\n * if (isFormGroup(group)) {\n * // group is FormGroup\n * }\n */\nexport function isFormGroup(data: unknown): data is FormGroup {\n return data instanceof FormGroup;\n}\n\n/**\n * Проверяет, является ли значение экземпляром FormArray\n * @example\n * const array = new FormArray([new FormControl('')]);\n * if (isFormArray(array)) {\n * // array is FormArray\n * }\n */\nexport function isFormArray(data: unknown): data is FormArray {\n return data instanceof FormArray;\n}\n\n/**\n * Проверяет, является ли значение экземпляром FormRecord\n * @example\n * const record = new FormRecord({ field: new FormControl('') });\n * if (isFormRecord(record)) {\n * // record is FormRecord\n * }\n */\nexport function isFormRecord(data: unknown): data is FormRecord {\n return data instanceof FormRecord;\n}\n\n/**\n * Проверяет, является ли значение экземпляром ViewContainerRef\n * @example\n * class MyComponent {\n * constructor(public vcr: ViewContainerRef) {}\n *\n * checkType() {\n * if (isViewContainer(this.vcr)) {\n * // this.vcr is ViewContainerRef\n * }\n * }\n * }\n */\nexport function isViewContainer(data: unknown): data is ViewContainerRef {\n return data instanceof ViewContainerRef;\n}\n\n/**\n * Проверяет, является ли значение экземпляром ComponentRef\n * @example\n * const componentRef = this.componentFactory.create(injector);\n * if (isComponentRef<MyComponent>(componentRef)) {\n * // componentRef is ComponentRef<MyComponent>\n * }\n */\nexport function isComponentRef<Instance>(data: unknown): data is ComponentRef<Instance> {\n return data instanceof ComponentRef;\n}\n\n/**\n * Проверяет, является ли значение экземпляром NgComponentOutlet\n * @example\n * class HostComponent {\n * checkOutlet(outlet: unknown) {\n * if (isComponentOutlet(outlet)) {\n * // outlet is NgComponentOutlet\n * }\n * }\n * }\n */\nexport function isComponentOutlet(data: unknown): data is NgComponentOutlet {\n return data instanceof NgComponentOutlet;\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;AAEA;;;;;;AAMG;AACG,SAAU,gBAAgB,CAAC,OAAoB,EAAA;AACnD,IAAA,OAAO,IAAI,UAAU,CAAC,UAAU,IAAG;AACjC,QAAA,MAAM,cAAc,GAAG,IAAI,cAAc,CAAC,OAAO,IAAG;AAClD,YAAA,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC;AAC1B,QAAA,CAAC,CAAC;AAEF,QAAA,cAAc,CAAC,OAAO,CAAC,OAAO,CAAC;AAE/B,QAAA,OAAO,MAAK;AACV,YAAA,cAAc,CAAC,SAAS,CAAC,OAAO,CAAC;AACnC,QAAA,CAAC;AACH,IAAA,CAAC,CAAC;AACJ;;ACnBA;;;;;;;;;;;AAWG;AACG,SAAU,oBAAoB,CAAC,KAAc,EAAA;AACjD,IAAA,OAAO,gBAAgB,CAAC,KAAK,CAAC,IAAI,SAAS;AAC7C;;ACZA;;;;;;;AAOG;AACG,SAAU,aAAa,CAAc,IAAa,EAAA;IACtD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