@fivelab/web-utils 1.0.8 → 1.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,5 @@
1
+ import { createElement } from '../dom/create-element.js';
2
+
1
3
  let scriptsMap = new Map();
2
4
  let stylesMap = new Map();
3
5
  function findScriptByKey(key) {
@@ -26,18 +28,13 @@ function appendScript(src, options = {}) {
26
28
  return ready;
27
29
  }
28
30
  const promise = new Promise((resolve, reject) => {
29
- const script = document.createElement('script');
30
- script.src = src;
31
- script.type = options.type ?? 'text/javascript';
32
- if (options.async !== undefined) {
33
- script.async = options.async;
34
- }
35
- if (options.defer !== undefined) {
36
- script.defer = options.defer;
37
- }
38
- if (options.attributes) {
39
- Object.entries(options.attributes).forEach(([k, v]) => script.setAttribute(k, v));
40
- }
31
+ const script = createElement('script', {
32
+ src: src,
33
+ type: options.type ?? 'text/javascript',
34
+ async: options.async,
35
+ defer: options.defer,
36
+ attrs: options.attributes,
37
+ });
41
38
  const cleanup = () => {
42
39
  script.removeEventListener('load', onLoad);
43
40
  script.removeEventListener('error', onError);
@@ -72,15 +69,12 @@ function appendStyle(href, options = {}) {
72
69
  return ready;
73
70
  }
74
71
  const promise = new Promise((resolve, reject) => {
75
- const link = document.createElement('link');
76
- link.rel = 'stylesheet';
77
- link.href = href;
78
- if (options.media) {
79
- link.media = options.media;
80
- }
81
- if (options.attributes) {
82
- Object.entries(options.attributes).forEach(([k, v]) => link.setAttribute(k, v));
83
- }
72
+ const link = createElement('link', {
73
+ href: href,
74
+ rel: 'stylesheet',
75
+ media: options.media,
76
+ attrs: options.attributes,
77
+ });
84
78
  const onLoad = () => {
85
79
  resolve(link);
86
80
  };
@@ -1 +1 @@
1
- {"version":3,"file":"assets.js","sources":["../../src/browser/assets.ts"],"sourcesContent":["export type AppendScriptOptions = {\n type?: string;\n async?: boolean;\n defer?: boolean;\n attributes?: Record<string, string>;\n};\n\nexport type AppendStyleOptions = {\n media?: string;\n attributes?: Record<string, string>;\n};\n\nexport type AppendAssetOptions = | AppendScriptOptions | AppendStyleOptions;\n\nlet scriptsMap = new Map<string, Promise<HTMLScriptElement>>();\nlet stylesMap = new Map<string, Promise<HTMLLinkElement>>();\n\nfunction findScriptByKey(key: string): HTMLScriptElement | undefined {\n const scripts = document.getElementsByTagName('script');\n\n return Array.from(scripts).find((e) => e.src === key);\n}\n\nfunction findStyleByKey(key: string): HTMLLinkElement | undefined {\n const links = document.getElementsByTagName('link');\n\n return Array.from(links).find((e) => e.rel === 'stylesheet' && e.href === key);\n}\n\nfunction getExtension(url: string): string | null {\n const clean = url.split('#')[0]!.split('?')[0]!; // eslint-disable-line @typescript-eslint/no-non-null-assertion\n const idx = clean.lastIndexOf('.');\n\n return idx >= 0 ? clean.slice(idx + 1).toLowerCase() : null;\n}\n\nexport function appendScript(src: string, options: AppendScriptOptions = {}): Promise<HTMLScriptElement> {\n const key = new URL(src, document.baseURI).href;\n\n const cached = scriptsMap.get(key);\n\n if (cached) {\n return cached;\n }\n\n const existing = findScriptByKey(key);\n\n if (existing) {\n const ready = Promise.resolve(existing);\n scriptsMap.set(key, ready);\n\n return ready;\n }\n\n const promise: Promise<HTMLScriptElement> = new Promise((resolve, reject) => {\n const script = document.createElement('script');\n\n script.src = src;\n script.type = options.type ?? 'text/javascript';\n\n if (options.async !== undefined) {\n script.async = options.async;\n }\n\n if (options.defer !== undefined) {\n script.defer = options.defer;\n }\n\n if (options.attributes) {\n Object.entries(options.attributes).forEach(([k, v]) => script.setAttribute(k, v));\n }\n\n const cleanup = () => {\n script.removeEventListener('load', onLoad);\n script.removeEventListener('error', onError);\n };\n\n const onLoad = () => {\n resolve(script);\n cleanup();\n };\n\n const onError = () => {\n script.remove();\n scriptsMap.delete(key);\n\n reject(new Error(`Failed to load script: ${src}`));\n\n cleanup();\n };\n\n script.addEventListener('load', onLoad);\n script.addEventListener('error', onError);\n\n document.head.appendChild(script);\n });\n\n scriptsMap.set(key, promise);\n\n return promise;\n}\n\nexport function appendStyle(href: string, options: AppendStyleOptions = {}): Promise<HTMLLinkElement> {\n const key = new URL(href, document.baseURI).href;\n\n const cached = stylesMap.get(key);\n\n if (cached) {\n return cached;\n }\n\n const existing = findStyleByKey(key);\n\n if (existing) {\n const ready = Promise.resolve(existing);\n stylesMap.set(key, ready);\n\n return ready;\n }\n\n const promise = new Promise<HTMLLinkElement>((resolve, reject) => {\n const link = document.createElement('link');\n\n link.rel = 'stylesheet';\n link.href = href;\n\n if (options.media) {\n link.media = options.media;\n }\n\n if (options.attributes) {\n Object.entries(options.attributes).forEach(([k, v]) => link.setAttribute(k, v));\n }\n\n const onLoad = () => {\n resolve(link);\n };\n\n const onError = () => {\n link.remove();\n stylesMap.delete(key);\n\n reject(new Error(`Failed to load stylesheet: ${href}`));\n };\n\n link.addEventListener('load', onLoad, { once: true });\n link.addEventListener('error', onError, { once: true });\n\n document.head.appendChild(link);\n });\n\n stylesMap.set(key, promise);\n\n return promise;\n}\n\nexport function appendAsset(url: string, options: AppendAssetOptions = {}): Promise<HTMLScriptElement | HTMLLinkElement> {\n const ext = getExtension(url);\n\n if (ext === 'css') {\n return appendStyle(url, options as AppendStyleOptions);\n }\n\n if (ext === 'js' || ext === 'mjs') {\n return appendScript(url, options as AppendScriptOptions);\n }\n\n throw new Error(`Unsupported asset type for \"${url}\". Expected \".css\", \".js\" or \".mjs\".`);\n}\n\nexport const __test__ = import.meta.env?.MODE === 'test'\n ? {\n reset: () => {\n scriptsMap = new Map();\n stylesMap = new Map();\n },\n }\n : undefined;\n\n"],"names":[],"mappings":"AAcA,IAAI,UAAU,GAAG,IAAI,GAAG,EAAsC;AAC9D,IAAI,SAAS,GAAG,IAAI,GAAG,EAAoC;AAE3D,SAAS,eAAe,CAAC,GAAW,EAAA;IAChC,MAAM,OAAO,GAAG,QAAQ,CAAC,oBAAoB,CAAC,QAAQ,CAAC;IAEvD,OAAO,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,C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EAAE;AACtB,YAAA,SAAS,GAAG,IAAI,GAAG,EAAE;QACzB,CAAC;AACJ;MACC;;;;"}
1
+ {"version":3,"file":"assets.js","sources":["../../src/browser/assets.ts"],"sourcesContent":["import { createElement } from '../dom';\n\nexport type AppendScriptOptions = {\n type?: string;\n async?: boolean;\n defer?: boolean;\n attributes?: Record<string, string>;\n};\n\nexport type AppendStyleOptions = {\n media?: string;\n attributes?: Record<string, string>;\n};\n\nexport type AppendAssetOptions = | AppendScriptOptions | AppendStyleOptions;\n\nlet scriptsMap = new Map<string, Promise<HTMLScriptElement>>();\nlet stylesMap = new Map<string, Promise<HTMLLinkElement>>();\n\nfunction findScriptByKey(key: string): HTMLScriptElement | undefined {\n const scripts = document.getElementsByTagName('script');\n\n return Array.from(scripts).find((e) => e.src === key);\n}\n\nfunction findStyleByKey(key: string): HTMLLinkElement | undefined {\n const links = document.getElementsByTagName('link');\n\n return Array.from(links).find((e) => e.rel === 'stylesheet' && e.href === key);\n}\n\nfunction getExtension(url: string): string | null {\n const clean = url.split('#')[0]!.split('?')[0]!; // eslint-disable-line @typescript-eslint/no-non-null-assertion\n const idx = clean.lastIndexOf('.');\n\n return idx >= 0 ? clean.slice(idx + 1).toLowerCase() : null;\n}\n\nexport function appendScript(src: string, options: AppendScriptOptions = {}): Promise<HTMLScriptElement> {\n const key = new URL(src, document.baseURI).href;\n\n const cached = scriptsMap.get(key);\n\n if (cached) {\n return cached;\n }\n\n const existing = findScriptByKey(key);\n\n if (existing) {\n const ready = Promise.resolve(existing);\n scriptsMap.set(key, ready);\n\n return ready;\n }\n\n const promise: Promise<HTMLScriptElement> = new Promise((resolve, reject) => {\n const script = createElement('script', {\n src: src,\n type: options.type ?? 'text/javascript',\n async: options.async,\n defer: options.defer,\n attrs: options.attributes,\n });\n\n const cleanup = () => {\n script.removeEventListener('load', onLoad);\n script.removeEventListener('error', onError);\n };\n\n const onLoad = () => {\n resolve(script);\n cleanup();\n };\n\n const onError = () => {\n script.remove();\n scriptsMap.delete(key);\n\n reject(new Error(`Failed to load script: ${src}`));\n\n cleanup();\n };\n\n script.addEventListener('load', onLoad);\n script.addEventListener('error', onError);\n\n document.head.appendChild(script);\n });\n\n scriptsMap.set(key, promise);\n\n return promise;\n}\n\nexport function appendStyle(href: string, options: AppendStyleOptions = {}): Promise<HTMLLinkElement> {\n const key = new URL(href, document.baseURI).href;\n\n const cached = stylesMap.get(key);\n\n if (cached) {\n return cached;\n }\n\n const existing = findStyleByKey(key);\n\n if (existing) {\n const ready = Promise.resolve(existing);\n stylesMap.set(key, ready);\n\n return ready;\n }\n\n const promise = new Promise<HTMLLinkElement>((resolve, reject) => {\n const link = createElement('link', {\n href: href,\n rel: 'stylesheet',\n media: options.media,\n attrs: options.attributes,\n });\n\n const onLoad = () => {\n resolve(link);\n };\n\n const onError = () => {\n link.remove();\n stylesMap.delete(key);\n\n reject(new Error(`Failed to load stylesheet: ${href}`));\n };\n\n link.addEventListener('load', onLoad, { once: true });\n link.addEventListener('error', onError, { once: true });\n\n document.head.appendChild(link);\n });\n\n stylesMap.set(key, promise);\n\n return promise;\n}\n\nexport function appendAsset(url: string, options: AppendAssetOptions = {}): Promise<HTMLScriptElement | HTMLLinkElement> {\n const ext = getExtension(url);\n\n if (ext === 'css') {\n return appendStyle(url, options as AppendStyleOptions);\n }\n\n if (ext === 'js' || ext === 'mjs') {\n return appendScript(url, options as AppendScriptOptions);\n }\n\n throw new Error(`Unsupported asset type for \"${url}\". Expected \".css\", \".js\" or \".mjs\".`);\n}\n\nexport const __test__ = import.meta.env?.MODE === 'test'\n ? {\n reset: () => {\n scriptsMap = new Map();\n stylesMap = new Map();\n },\n }\n : undefined;\n\n"],"names":[],"mappings":";;AAgBA,IAAI,UAAU,GAAG,IAAI,GAAG,EAAsC;AAC9D,IAAI,SAAS,GAAG,IAAI,GAAG,EAAoC;AAE3D,SAAS,eAAe,CAAC,GAAW,EAAA;IAChC,MAAM,OAAO,GAAG,QAAQ,CAAC,oBAAoB,CAAC,QAA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AAC;AACnC,IAAA,CAAC,CAAC;AAEF,IAAA,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC;AAE3B,IAAA,OAAO,OAAO;AAClB;SAEgB,WAAW,CAAC,GAAW,EAAE,UAA8B,EAAE,EAAA;AACrE,IAAA,MAAM,GAAG,GAAG,YAAY,CAAC,GAAG,CAAC;AAE7B,IAAA,IAAI,GAAG,KAAK,KAAK,EAAE;AACf,QAAA,OAAO,WAAW,CAAC,GAAG,EAAE,OAA6B,CAAC;IAC1D;IAEA,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,KAAK,EAAE;AAC/B,QAAA,OAAO,YAAY,CAAC,GAAG,EAAE,OAA8B,CAAC;IAC5D;AAEA,IAAA,MAAM,IAAI,KAAK,CAAC,+BAA+B,GAAG,CAAA,oCAAA,CAAsC,CAAC;AAC7F;AAEO,MAAM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,KAAK;AAC9C,MAAE;QACE,KAAK,EAAE,MAAK;AACR,YAAA,UAAU,GAAG,IAAI,GAAG,EAAE;AACtB,YAAA,SAAS,GAAG,IAAI,GAAG,EAAE;QACzB,CAAC;AACJ;MACC;;;;"}
@@ -8,7 +8,7 @@ export type UploadRequestInit = Omit<RequestInit, 'body'> & {
8
8
  readonly body: FormData;
9
9
  readonly uploadProgress?: UploadProgressCallback;
10
10
  };
11
- export declare function request(url: string): Promise<Response>;
12
- export declare function request(url: string, init?: RequestInit): Promise<Response>;
13
- export declare function request(url: string, init: UploadRequestInit): Promise<Response>;
11
+ export declare function request(url: URL | string): Promise<Response>;
12
+ export declare function request(url: URL | string, init?: RequestInit): Promise<Response>;
13
+ export declare function request(url: URL | string, init: UploadRequestInit): Promise<Response>;
14
14
  export {};
@@ -68,6 +68,9 @@ function parseXhrHeaders(raw) {
68
68
  return headers;
69
69
  }
70
70
  function request(url, init) {
71
+ if (url instanceof URL) {
72
+ url = url.href;
73
+ }
71
74
  if (init && isUploadRequestInit(init)) {
72
75
  return xhrRequest(url, init);
73
76
  }
@@ -1 +1 @@
1
- {"version":3,"file":"request.js","sources":["../../src/browser/request.ts"],"sourcesContent":["type ProgressInfoEvent = {\n readonly loaded: number;\n readonly total: number;\n readonly progress: number;\n}\n\nexport type UploadProgressCallback = (progress: ProgressInfoEvent) => void;\n\nexport type UploadRequestInit = Omit<RequestInit, 'body'> & {\n readonly body: FormData;\n readonly uploadProgress?: UploadProgressCallback;\n}\n\nfunction isUploadRequestInit(init?: RequestInit): init is UploadRequestInit {\n return typeof init === 'object'\n && init !== null\n && 'uploadProgress' in init\n && typeof (init as UploadRequestInit).uploadProgress === 'function';\n}\n\nfunction xhrRequest(url: string, init: UploadRequestInit): Promise<Response> {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(init.method ?? 'POST', url, true);\n\n // Add headers\n if (init.headers) {\n Object.entries(init.headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n }\n\n // Add pass credentials\n if (init.credentials) {\n xhr.withCredentials = true;\n }\n\n // Add abort signal\n const signal = init.signal;\n const onAbort = () => {\n xhr.abort();\n\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n if (signal) {\n if (signal.aborted) {\n return onAbort();\n }\n\n signal.addEventListener('abort', onAbort, {\n once: true,\n });\n }\n\n xhr.upload.onprogress = (e) => {\n if (!e.lengthComputable) {\n return;\n }\n\n init.uploadProgress?.({\n loaded: e.loaded,\n total: e.total,\n progress: Math.round((e.loaded / e.total) * 100),\n });\n };\n\n xhr.onerror = () => {\n reject(new Error('XHR network error'));\n };\n\n xhr.ontimeout = () => {\n reject(new Error('XHR timeout error'));\n };\n\n xhr.onload = () => {\n resolve(new Response(xhr.response, {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseXhrHeaders(xhr.getAllResponseHeaders()),\n }));\n };\n\n xhr.responseType = 'arraybuffer';\n xhr.send(init.body);\n });\n}\n\nfunction parseXhrHeaders(raw: string): Headers {\n const headers = new Headers();\n\n raw.trim().split(/[\\r\\n]+/).forEach((line) => {\n const idx = line.indexOf(':');\n\n if (idx > 0) {\n headers.append(line.slice(0, idx).trim(), line.slice(idx + 1).trim());\n }\n });\n\n return headers;\n}\n\nexport function request(url: string): Promise<Response>;\nexport function request(url: string, init?: RequestInit): Promise<Response>;\nexport function request(url: string, init: UploadRequestInit): Promise<Response>;\n\nexport function request(url: string, init?: unknown): Promise<Response> {\n if (init && isUploadRequestInit(init)) {\n return xhrRequest(url, init);\n }\n\n return fetch(url, init as RequestInit | undefined);\n}\n"],"names":[],"mappings":"AAaA,SAAS,mBAAmB,CAAC,IAAkB,EAAA;IAC3C,OAAO,OAAO,IAAI,KAAK;AAChB,WAAA,IAAI,KAAK;AACT,WAAA,gBAAgB,IAAI;AACpB,WAAA,OAAQ,IAA0B,CAAC,cAAc,KAAK,UAAU;AAC3E;AAEA,SAAS,UAAU,CAAC,GAAW,EAAE,IAAuB,EAAA;IACpD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,KAAI;AACnC,QAAA,MAAM,GAAG,GAAG,IAAI,cAAc,EAAE;AAChC,QAAA,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC;;AAG1C,QAAA,IAAI,IAAI,CAAC,OAAO,EAAE;AACd,YAAA,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,GAAG,CAAC,gBAAgB,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC9F;;AAGA,QAAA,IAAI,IAAI,CAAC,WAAW,EAAE;AAClB,YAAA,GAAG,CAAC,eAAe,GAAG,IAAI;QAC9B;;AAGA,QAAA,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM;QAC1B,MAAM,OAAO,GAAG,MAAK;YACjB,GAAG,CAAC,KAAK,EAAE;YA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AC,YAAY,GAAG,aAAa;AAChC,QAAA,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;AACvB,IAAA,CAAC,CAAC;AACN;AAEA,SAAS,eAAe,CAAC,GAAW,EAAA;AAChC,IAAA,MAAM,OAAO,GAAG,IAAI,OAAO,EAAE;AAE7B,IAAA,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,KAAI;QACzC,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC;AAE7B,QAAA,IAAI,GAAG,GAAG,CAAC,EAAE;YACT,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACzE;AACJ,IAAA,CAAC,CAAC;AAEF,IAAA,OAAO,OAAO;AAClB;AAMM,SAAU,OAAO,CAAC,GAAW,EAAE,IAAc,EAAA;AAC/C,IAAA,IAAI,IAAI,IAAI,mBAAmB,CAAC,IAAI,CAAC,EAAE;AACnC,QAAA,OAAO,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC;IAChC;AAEA,IAAA,OAAO,KAAK,CAAC,GAAG,EAAE,IAA+B,CAAC;AACtD;;;;"}
1
+ {"version":3,"file":"request.js","sources":["../../src/browser/request.ts"],"sourcesContent":["type ProgressInfoEvent = {\n readonly loaded: number;\n readonly total: number;\n readonly progress: number;\n}\n\nexport type UploadProgressCallback = (progress: ProgressInfoEvent) => void;\n\nexport type UploadRequestInit = Omit<RequestInit, 'body'> & {\n readonly body: FormData;\n readonly uploadProgress?: UploadProgressCallback;\n}\n\nfunction isUploadRequestInit(init?: RequestInit): init is UploadRequestInit {\n return typeof init === 'object'\n && init !== null\n && 'uploadProgress' in init\n && typeof (init as UploadRequestInit).uploadProgress === 'function';\n}\n\nfunction xhrRequest(url: string, init: UploadRequestInit): Promise<Response> {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(init.method ?? 'POST', url, true);\n\n // Add headers\n if (init.headers) {\n Object.entries(init.headers).forEach(([name, value]) => xhr.setRequestHeader(name, value));\n }\n\n // Add pass credentials\n if (init.credentials) {\n xhr.withCredentials = true;\n }\n\n // Add abort signal\n const signal = init.signal;\n const onAbort = () => {\n xhr.abort();\n\n reject(new DOMException('Aborted', 'AbortError'));\n };\n\n if (signal) {\n if (signal.aborted) {\n return onAbort();\n }\n\n signal.addEventListener('abort', onAbort, {\n once: true,\n });\n }\n\n xhr.upload.onprogress = (e) => {\n if (!e.lengthComputable) {\n return;\n }\n\n init.uploadProgress?.({\n loaded: e.loaded,\n total: e.total,\n progress: Math.round((e.loaded / e.total) * 100),\n });\n };\n\n xhr.onerror = () => {\n reject(new Error('XHR network error'));\n };\n\n xhr.ontimeout = () => {\n reject(new Error('XHR timeout error'));\n };\n\n xhr.onload = () => {\n resolve(new Response(xhr.response, {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseXhrHeaders(xhr.getAllResponseHeaders()),\n }));\n };\n\n xhr.responseType = 'arraybuffer';\n xhr.send(init.body);\n });\n}\n\nfunction parseXhrHeaders(raw: string): Headers {\n const headers = new Headers();\n\n raw.trim().split(/[\\r\\n]+/).forEach((line) => {\n const idx = line.indexOf(':');\n\n if (idx > 0) {\n headers.append(line.slice(0, idx).trim(), line.slice(idx + 1).trim());\n }\n });\n\n return headers;\n}\n\nexport function request(url: URL | string): Promise<Response>;\nexport function request(url: URL | string, init?: RequestInit): Promise<Response>;\nexport function request(url: URL | string, init: UploadRequestInit): Promise<Response>;\n\nexport function request(url: URL | string, init?: unknown): Promise<Response> {\n if (url instanceof URL) {\n url = url.href;\n }\n\n if (init && isUploadRequestInit(init)) {\n return xhrRequest(url, init);\n }\n\n return fetch(url, init as RequestInit | undefined);\n}\n"],"names":[],"mappings":"AAaA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IAAI,GAAG,GAAG,CAAC,EAAE;YACT,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACzE;AACJ,IAAA,CAAC,CAAC;AAEF,IAAA,OAAO,OAAO;AAClB;AAMM,SAAU,OAAO,CAAC,GAAiB,EAAE,IAAc,EAAA;AACrD,IAAA,IAAI,GAAG,YAAY,GAAG,EAAE;AACpB,QAAA,GAAG,GAAG,GAAG,CAAC,IAAI;IAClB;AAEA,IAAA,IAAI,IAAI,IAAI,mBAAmB,CAAC,IAAI,CAAC,EAAE;AACnC,QAAA,OAAO,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC;IAChC;AAEA,IAAA,OAAO,KAAK,CAAC,GAAG,EAAE,IAA+B,CAAC;AACtD;;;;"}
@@ -0,0 +1,44 @@
1
+ type AttributeValue = string | number | boolean | null | undefined;
2
+ type ContentOptions = {
3
+ text?: string;
4
+ html?: never;
5
+ } | {
6
+ html?: string;
7
+ text?: never;
8
+ } | {
9
+ text?: undefined;
10
+ html?: undefined;
11
+ };
12
+ export type CommonOptions = {
13
+ id?: string;
14
+ dataset?: Record<string, AttributeValue>;
15
+ attrs?: Record<string, AttributeValue>;
16
+ };
17
+ export type BaseOptions = CommonOptions & {
18
+ classList?: string[];
19
+ style?: Partial<CSSStyleDeclaration>;
20
+ } & ContentOptions;
21
+ export type AnchorOptions = BaseOptions & {
22
+ href?: URL | string;
23
+ target?: '_blank' | '_self' | '_parent' | '_top' | (string & {});
24
+ };
25
+ export type ScriptOptions = CommonOptions & {
26
+ src?: URL | string;
27
+ type?: 'module' | 'importmap' | 'text/javascript' | (string & {});
28
+ async?: boolean;
29
+ defer?: boolean;
30
+ };
31
+ export type LinkOptions = CommonOptions & {
32
+ as?: string;
33
+ rel?: 'stylesheet' | (string & {});
34
+ href?: URL | string;
35
+ type?: string;
36
+ media?: string;
37
+ title?: string;
38
+ };
39
+ type TagsWithCustomOptions = 'a' | 'script' | 'link';
40
+ export declare function createElement(tag: 'a', options: AnchorOptions): HTMLAnchorElement;
41
+ export declare function createElement(tag: 'script', options: ScriptOptions): HTMLScriptElement;
42
+ export declare function createElement(tag: 'link', options: LinkOptions): HTMLLinkElement;
43
+ export declare function createElement<K extends Exclude<keyof HTMLElementTagNameMap, TagsWithCustomOptions>>(tag: K, options?: BaseOptions): HTMLElementTagNameMap[K];
44
+ export {};
@@ -0,0 +1,98 @@
1
+ function normalizeAttributeValue(value, dataset = false) {
2
+ if (typeof value === 'undefined' || null === value) {
3
+ return null;
4
+ }
5
+ if (typeof value === 'boolean') {
6
+ return value ? (dataset ? 'true' : '1') : (dataset ? 'false' : '0');
7
+ }
8
+ return String(value);
9
+ }
10
+ function applyAnchorOptions(el, options) {
11
+ if (options.href !== undefined) {
12
+ el.href = options.href instanceof URL ? options.href.href : options.href;
13
+ }
14
+ if (options.target !== undefined) {
15
+ el.target = options.target;
16
+ }
17
+ }
18
+ function applyScriptOptions(el, options) {
19
+ if (options.src) {
20
+ el.src = options.src instanceof URL ? options.src.href : options.src;
21
+ }
22
+ if (options.type !== undefined) {
23
+ el.type = options.type;
24
+ }
25
+ if (options.async !== undefined) {
26
+ el.async = options.async;
27
+ }
28
+ if (options.defer !== undefined) {
29
+ el.defer = options.defer;
30
+ }
31
+ }
32
+ function applyLinkOptions(el, options) {
33
+ if (options.as !== undefined) {
34
+ el.as = options.as;
35
+ }
36
+ if (options.rel !== undefined) {
37
+ el.rel = options.rel;
38
+ }
39
+ if (options.href !== undefined) {
40
+ el.href = options.href instanceof URL ? options.href.href : options.href;
41
+ }
42
+ if (options.type !== undefined) {
43
+ el.type = options.type;
44
+ }
45
+ if (options.media !== undefined) {
46
+ el.media = options.media;
47
+ }
48
+ if (options.title !== undefined) {
49
+ el.title = options.title;
50
+ }
51
+ }
52
+ function createElement(tag, options = {}) {
53
+ const el = document.createElement(tag);
54
+ if (options.id) {
55
+ el.id = options.id;
56
+ }
57
+ if (options.classList && options.classList.length) {
58
+ el.classList.add(...options.classList);
59
+ }
60
+ if (options.dataset) {
61
+ Object.entries(options.dataset).forEach(([k, v]) => {
62
+ v = normalizeAttributeValue(v, true);
63
+ if (null !== v) {
64
+ (el.dataset)[k] = v;
65
+ }
66
+ });
67
+ }
68
+ if (options.attrs) {
69
+ Object.entries(options.attrs).forEach(([k, v]) => {
70
+ v = normalizeAttributeValue(v, false);
71
+ if (null !== v) {
72
+ el.setAttribute(k, v);
73
+ }
74
+ });
75
+ }
76
+ if (options.text !== undefined) {
77
+ el.textContent = options.text;
78
+ }
79
+ if (options.html !== undefined) {
80
+ el.innerHTML = options.html;
81
+ }
82
+ if (options.style) {
83
+ Object.assign(el.style, options.style);
84
+ }
85
+ if ('a' === tag) {
86
+ applyAnchorOptions(el, options);
87
+ }
88
+ if ('script' === tag) {
89
+ applyScriptOptions(el, options);
90
+ }
91
+ if ('link' === tag) {
92
+ applyLinkOptions(el, options);
93
+ }
94
+ return el;
95
+ }
96
+
97
+ export { createElement };
98
+ //# sourceMappingURL=create-element.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-element.js","sources":["../../src/dom/create-element.ts"],"sourcesContent":["type AttributeValue = string | number | boolean | null | undefined;\n\ntype ContentOptions =\n | { text?: string; html?: never }\n | { html?: string; text?: never }\n | { text?: undefined; html?: undefined };\n\nexport type CommonOptions = {\n id?: string;\n dataset?: Record<string, AttributeValue>;\n attrs?: Record<string, AttributeValue>;\n};\n\nexport type BaseOptions = CommonOptions & {\n classList?: string[];\n style?: Partial<CSSStyleDeclaration>;\n} & ContentOptions;\n\nexport type AnchorOptions = BaseOptions & {\n href?: URL | string;\n target?: '_blank' | '_self' | '_parent' | '_top' | (string & {});\n}\n\nexport type ScriptOptions = CommonOptions & {\n src?: URL | string;\n type?: 'module' | 'importmap' | 'text/javascript' | (string & {});\n async?: boolean;\n defer?: boolean;\n};\n\nexport type LinkOptions = CommonOptions & {\n as?: string;\n rel?: 'stylesheet' | (string & {});\n href?: URL | string;\n type?: string;\n media?: string;\n title?: string;\n}\n\ntype TagsWithCustomOptions = 'a' | 'script' | 'link';\n\nfunction normalizeAttributeValue(value: AttributeValue, dataset = false): string | null {\n if (typeof value === 'undefined' || null === value) {\n return null;\n }\n\n if (typeof value === 'boolean') {\n return value ? (dataset ? 'true' : '1') : (dataset ? 'false' : '0');\n }\n\n return String(value);\n}\n\nfunction applyAnchorOptions(el: HTMLAnchorElement, options: AnchorOptions): void {\n if (options.href !== undefined) {\n el.href = options.href instanceof URL ? options.href.href : options.href;\n }\n\n if (options.target !== undefined) {\n el.target = options.target;\n }\n}\n\nfunction applyScriptOptions(el: HTMLScriptElement, options: ScriptOptions): void {\n if (options.src) {\n el.src = options.src instanceof URL ? options.src.href : options.src;\n }\n\n if (options.type !== undefined) {\n el.type = options.type;\n }\n\n if (options.async !== undefined) {\n el.async = options.async;\n }\n\n if (options.defer !== undefined) {\n el.defer = options.defer;\n }\n}\n\nfunction applyLinkOptions(el: HTMLLinkElement, options: LinkOptions): void {\n if (options.as !== undefined) {\n el.as = options.as;\n }\n\n if (options.rel !== undefined) {\n el.rel = options.rel;\n }\n\n if (options.href !== undefined) {\n el.href = options.href instanceof URL ? options.href.href : options.href;\n }\n\n if (options.type !== undefined) {\n el.type = options.type;\n }\n\n if (options.media !== undefined) {\n el.media = options.media;\n }\n\n if (options.title !== undefined) {\n el.title = options.title;\n }\n}\n\nexport function createElement(tag: 'a', options: AnchorOptions): HTMLAnchorElement;\nexport function createElement(tag: 'script', options: ScriptOptions): HTMLScriptElement;\nexport function createElement(tag: 'link', options: LinkOptions): HTMLLinkElement;\nexport function createElement<K extends Exclude<keyof HTMLElementTagNameMap, TagsWithCustomOptions>>(tag: K, options?: BaseOptions): HTMLElementTagNameMap[K];\n\nexport function createElement(tag: string, options: BaseOptions = {}): HTMLElement {\n const el = document.createElement(tag);\n\n if (options.id) {\n el.id = options.id;\n }\n\n if (options.classList && options.classList.length) {\n el.classList.add(...options.classList);\n }\n\n if (options.dataset) {\n Object.entries(options.dataset).forEach(([k, v]) => {\n v = normalizeAttributeValue(v, true);\n\n if (null !== v) {\n (el.dataset)[k] = v;\n }\n });\n }\n\n if (options.attrs) {\n Object.entries(options.attrs).forEach(([k, v]) => {\n v = normalizeAttributeValue(v, false);\n\n if (null !== v) {\n el.setAttribute(k, v);\n }\n });\n }\n\n if (options.text !== undefined) {\n el.textContent = options.text;\n }\n\n if (options.html !== undefined) {\n el.innerHTML = options.html;\n }\n\n if (options.style) {\n Object.assign(el.style, options.style);\n }\n\n if ('a' === tag) {\n applyAnchorOptions(el as HTMLAnchorElement, options as AnchorOptions);\n }\n\n if ('script' === tag) {\n applyScriptOptions(el as HTMLScriptElement, options as ScriptOptions);\n }\n\n if ('link' === tag) {\n applyLinkOptions(el as HTMLLinkElement, options as LinkOptions);\n }\n\n return el;\n}\n"],"names":[],"mappings":"AAyCA,SAAS,uBAAuB,CAAC,KAAqB,EAAE,OAAO,GAAG,KAAK,EAAA;IACnE,IAAI,OAAO,KAAK,KAAK,WAAW,IAAI,IAAI,KAAK,KAAK,EAAE;AAChD,QAAA,OAAO,IAAI;IACf;AAEA,IAAA,IAAI,OAAO,KAAK,KAAK,SAAS,EAAE;AAC5B,QAAA,OAAO,KAAK,IAAI,OAAO,GAAG,MAAM,GAAG,GAAG,KAAK,OAAO,GAAG,OAAO,GAAG,GAAG,CAAC;IACvE;AAEA,IAAA,OAAO,MAAM,CAAC,KAAK,CAAC;AACxB;AAEA,SAAS,kBAAkB,CAAC,EAAqB,EAAE,OAAsB,EAAA;AACrE,IAAA,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE;QAC5B,EAAE,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,YAAY,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI;IAC5E;AAEA,IAAA,IA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AC;AAErC,YAAA,IAAI,IAAI,KAAK,CAAC,EAAE;AACZ,gBAAA,EAAE,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC;YACzB;AACJ,QAAA,CAAC,CAAC;IACN;AAEA,IAAA,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE;AAC5B,QAAA,EAAE,CAAC,WAAW,GAAG,OAAO,CAAC,IAAI;IACjC;AAEA,IAAA,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE;AAC5B,QAAA,EAAE,CAAC,SAAS,GAAG,OAAO,CAAC,IAAI;IAC/B;AAEA,IAAA,IAAI,OAAO,CAAC,KAAK,EAAE;QACf,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC;IAC1C;AAEA,IAAA,IAAI,GAAG,KAAK,GAAG,EAAE;AACb,QAAA,kBAAkB,CAAC,EAAuB,EAAE,OAAwB,CAAC;IACzE;AAEA,IAAA,IAAI,QAAQ,KAAK,GAAG,EAAE;AAClB,QAAA,kBAAkB,CAAC,EAAuB,EAAE,OAAwB,CAAC;IACzE;AAEA,IAAA,IAAI,MAAM,KAAK,GAAG,EAAE;AAChB,QAAA,gBAAgB,CAAC,EAAqB,EAAE,OAAsB,CAAC;IACnE;AAEA,IAAA,OAAO,EAAE;AACb;;;;"}
@@ -1,6 +1,7 @@
1
1
  export * from './attributes';
2
2
  export * from './changes';
3
3
  export * from './classes';
4
+ export * from './create-element';
4
5
  export * from './events';
5
6
  export * from './form';
6
7
  export * from './html';
package/dist/dom/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { readBoolAttribute, readStringAttribute } from './attributes.js';
2
2
  export { onDomChanges } from './changes.js';
3
3
  export { addClass, removeClass } from './classes.js';
4
+ export { createElement } from './create-element.js';
4
5
  export { onDomEvents } from './events.js';
5
6
  export { endFormProcessing, readBooleanInput, readCheckboxValue, readElementValue, readFileInput, readFormData, readInputValue, readNumberInput, readRadioValue, startFormProcessing } from './form.js';
6
7
  export { createElementFromHtml, replaceElement, replaceHtmlString } from './html.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fivelab/web-utils",
3
- "version": "1.0.8",
3
+ "version": "1.0.9",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "The helpers for easy manipulate with dom.",