@stackframe/stack-shared 2.8.43 → 2.8.45

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.
Files changed (64) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/apps/apps-config.d.mts +52 -31
  3. package/dist/apps/apps-config.d.ts +52 -31
  4. package/dist/apps/apps-config.js +54 -32
  5. package/dist/apps/apps-config.js.map +1 -1
  6. package/dist/config/schema.d.mts +159 -159
  7. package/dist/config/schema.d.ts +159 -159
  8. package/dist/config/schema.js +1 -1
  9. package/dist/config/schema.js.map +1 -1
  10. package/dist/esm/apps/apps-config.js +52 -31
  11. package/dist/esm/apps/apps-config.js.map +1 -1
  12. package/dist/esm/config/schema.js +1 -1
  13. package/dist/esm/config/schema.js.map +1 -1
  14. package/dist/esm/interface/client-interface.js +18 -16
  15. package/dist/esm/interface/client-interface.js.map +1 -1
  16. package/dist/esm/utils/caches.js +6 -2
  17. package/dist/esm/utils/caches.js.map +1 -1
  18. package/dist/esm/utils/globals.js +9 -1
  19. package/dist/esm/utils/globals.js.map +1 -1
  20. package/dist/esm/utils/react.js +12 -6
  21. package/dist/esm/utils/react.js.map +1 -1
  22. package/dist/esm/utils/regex.js +13 -0
  23. package/dist/esm/utils/regex.js.map +1 -0
  24. package/dist/esm/utils/strings.js +1 -1
  25. package/dist/esm/utils/strings.js.map +1 -1
  26. package/dist/esm/utils/strings.nicify.test.js +6 -0
  27. package/dist/esm/utils/strings.nicify.test.js.map +1 -1
  28. package/dist/esm/utils/urls.js +10 -0
  29. package/dist/esm/utils/urls.js.map +1 -1
  30. package/dist/index.d.mts +1 -1
  31. package/dist/index.d.ts +1 -1
  32. package/dist/interface/admin-interface.d.mts +1 -1
  33. package/dist/interface/admin-interface.d.ts +1 -1
  34. package/dist/interface/client-interface.d.mts +1 -1
  35. package/dist/interface/client-interface.d.ts +1 -1
  36. package/dist/interface/client-interface.js +18 -16
  37. package/dist/interface/client-interface.js.map +1 -1
  38. package/dist/interface/server-interface.d.mts +1 -1
  39. package/dist/interface/server-interface.d.ts +1 -1
  40. package/dist/utils/caches.d.mts +4 -2
  41. package/dist/utils/caches.d.ts +4 -2
  42. package/dist/utils/caches.js +6 -2
  43. package/dist/utils/caches.js.map +1 -1
  44. package/dist/utils/globals.d.mts +3 -1
  45. package/dist/utils/globals.d.ts +3 -1
  46. package/dist/utils/globals.js +12 -2
  47. package/dist/utils/globals.js.map +1 -1
  48. package/dist/utils/react.d.mts +2 -1
  49. package/dist/utils/react.d.ts +2 -1
  50. package/dist/utils/react.js +13 -6
  51. package/dist/utils/react.js.map +1 -1
  52. package/dist/utils/regex.d.mts +3 -0
  53. package/dist/utils/regex.d.ts +3 -0
  54. package/dist/utils/regex.js +38 -0
  55. package/dist/utils/regex.js.map +1 -0
  56. package/dist/utils/strings.js +1 -1
  57. package/dist/utils/strings.js.map +1 -1
  58. package/dist/utils/strings.nicify.test.js +6 -0
  59. package/dist/utils/strings.nicify.test.js.map +1 -1
  60. package/dist/utils/urls.d.mts +3 -1
  61. package/dist/utils/urls.d.ts +3 -1
  62. package/dist/utils/urls.js +12 -0
  63. package/dist/utils/urls.js.map +1 -1
  64. package/package.json +1 -1
@@ -43,6 +43,7 @@ declare class AsyncCache<D extends any[], T> {
43
43
  readonly onStateChange: (key: D, callback: (value: T, oldValue: T | undefined) => void) => {
44
44
  unsubscribe: () => void;
45
45
  };
46
+ readonly isDirty: (key: D) => boolean;
46
47
  }
47
48
  declare class AsyncValueCache<T> {
48
49
  private readonly _options;
@@ -86,10 +87,11 @@ declare class AsyncValueCache<T> {
86
87
  */
87
88
  refresh(): Promise<T>;
88
89
  /**
89
- * Invalidates the cache, marking it to refresh on the next read. If anyone was listening to it, it will refresh
90
- * immediately.
90
+ * Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read). If anyone was listening to it,
91
+ * it will refresh immediately.
91
92
  */
92
93
  invalidate(): void;
94
+ isDirty(): boolean;
93
95
  onStateChange(callback: (value: T, oldValue: T | undefined) => void): {
94
96
  unsubscribe: () => void;
95
97
  };
@@ -52,6 +52,7 @@ var AsyncCache = class {
52
52
  this.refresh = this._createKeyed("refresh");
53
53
  this.invalidate = this._createKeyed("invalidate");
54
54
  this.onStateChange = this._createKeyed("onStateChange");
55
+ this.isDirty = this._createKeyed("isDirty");
55
56
  }
56
57
  _createKeyed(functionName) {
57
58
  return (key, ...args) => {
@@ -144,8 +145,8 @@ var AsyncValueCache = class {
144
145
  return await this.getOrWait("write-only");
145
146
  }
146
147
  /**
147
- * Invalidates the cache, marking it to refresh on the next read. If anyone was listening to it, it will refresh
148
- * immediately.
148
+ * Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read). If anyone was listening to it,
149
+ * it will refresh immediately.
149
150
  */
150
151
  invalidate() {
151
152
  this._store.setUnavailable();
@@ -154,6 +155,9 @@ var AsyncValueCache = class {
154
155
  (0, import_promises.runAsynchronously)(this.refresh());
155
156
  }
156
157
  }
158
+ isDirty() {
159
+ return this._pendingPromise === void 0;
160
+ }
157
161
  onStateChange(callback) {
158
162
  const storeObj = this._store.onChange(callback);
159
163
  (0, import_promises.runAsynchronously)(this.getOrWait("read-write"));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/caches.tsx"],"sourcesContent":["import { DependenciesMap } from \"./maps\";\nimport { filterUndefined } from \"./objects\";\nimport { RateLimitOptions, ReactPromise, pending, rateLimited, resolved, runAsynchronously, wait } from \"./promises\";\nimport { AsyncStore } from \"./stores\";\n\n/**\n * Can be used to cache the result of a function call, for example for the `use` hook in React.\n */\nexport function cacheFunction<F extends Function>(f: F): F {\n const dependenciesMap = new DependenciesMap<any, any>();\n\n return ((...args: any) => {\n if (dependenciesMap.has(args)) {\n return dependenciesMap.get(args);\n }\n\n const value = f(...args);\n dependenciesMap.set(args, value);\n return value;\n }) as any as F;\n}\nundefined?.test(\"cacheFunction\", ({ expect }) => {\n // Test with a simple function\n let callCount = 0;\n const add = (a: number, b: number) => {\n callCount++;\n return a + b;\n };\n\n const cachedAdd = cacheFunction(add);\n\n // First call should execute the function\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Second call with same args should use cached result\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Call with different args should execute the function again\n expect(cachedAdd(2, 3)).toBe(5);\n expect(callCount).toBe(2);\n\n // Test with a function that returns objects\n let objectCallCount = 0;\n const createObject = (id: number) => {\n objectCallCount++;\n return { id };\n };\n\n const cachedCreateObject = cacheFunction(createObject);\n\n // First call should execute the function\n const obj1 = cachedCreateObject(1);\n expect(obj1).toEqual({ id: 1 });\n expect(objectCallCount).toBe(1);\n\n // Second call with same args should use cached result\n const obj2 = cachedCreateObject(1);\n expect(obj2).toBe(obj1); // Same reference\n expect(objectCallCount).toBe(1);\n});\n\n\ntype CacheStrategy = \"write-only\" | \"read-write\" | \"never\";\n\nexport class AsyncCache<D extends any[], T> {\n private readonly _map = new DependenciesMap<D, AsyncValueCache<T>>();\n\n constructor(\n private readonly _fetcher: (dependencies: D) => Promise<T>,\n private readonly _options: {\n onSubscribe?: (key: D, refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n // nothing here yet\n }\n\n private _createKeyed<FunctionName extends keyof AsyncValueCache<T>>(\n functionName: FunctionName,\n ): (key: D, ...args: Parameters<AsyncValueCache<T>[FunctionName]>) => ReturnType<AsyncValueCache<T>[FunctionName]> {\n return (key: D, ...args) => {\n const valueCache = this.getValueCache(key);\n return (valueCache[functionName] as any).apply(valueCache, args);\n };\n }\n\n getValueCache(dependencies: D): AsyncValueCache<T> {\n let cache = this._map.get(dependencies);\n if (!cache) {\n cache = new AsyncValueCache(\n async () => await this._fetcher(dependencies),\n {\n ...this._options,\n onSubscribe: this._options.onSubscribe ? (cb) => this._options.onSubscribe!(dependencies, cb) : undefined,\n },\n );\n this._map.set(dependencies, cache);\n }\n return cache;\n }\n\n async refreshWhere(predicate: (dependencies: D) => boolean) {\n const promises: Promise<T>[] = [];\n for (const [dependencies, cache] of this._map) {\n if (predicate(dependencies)) {\n promises.push(cache.refresh());\n }\n }\n await Promise.all(promises);\n }\n\n readonly isCacheAvailable = this._createKeyed(\"isCacheAvailable\");\n readonly getIfCached = this._createKeyed(\"getIfCached\");\n readonly getOrWait = this._createKeyed(\"getOrWait\");\n readonly forceSetCachedValue = this._createKeyed(\"forceSetCachedValue\");\n readonly forceSetCachedValueAsync = this._createKeyed(\"forceSetCachedValueAsync\");\n readonly refresh = this._createKeyed(\"refresh\");\n readonly invalidate = this._createKeyed(\"invalidate\");\n readonly onStateChange = this._createKeyed(\"onStateChange\");\n}\n\nclass AsyncValueCache<T> {\n private _store: AsyncStore<T>;\n private _pendingPromise: ReactPromise<T> | undefined;\n private _fetcher: () => Promise<T>;\n private readonly _rateLimitOptions: Omit<RateLimitOptions, \"batchCalls\">;\n private _subscriptionsCount = 0;\n private _unsubscribers: (() => void)[] = [];\n private _mostRecentRefreshPromiseIndex = 0;\n\n constructor(\n fetcher: () => Promise<T>,\n private readonly _options: {\n onSubscribe?: (refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n this._store = new AsyncStore();\n this._rateLimitOptions = {\n concurrency: 1,\n throttleMs: 300,\n ...filterUndefined(_options.rateLimiter ?? {}),\n };\n\n\n this._fetcher = rateLimited(fetcher, {\n ...this._rateLimitOptions,\n batchCalls: true,\n });\n }\n\n isCacheAvailable(): boolean {\n return this._store.isAvailable();\n }\n\n getIfCached() {\n return this._store.get();\n }\n\n getOrWait(cacheStrategy: CacheStrategy): ReactPromise<T> {\n const cached = this.getIfCached();\n if (cacheStrategy === \"read-write\" && cached.status === \"ok\") {\n return resolved(cached.data);\n }\n\n return this._refetch(cacheStrategy);\n }\n\n private _set(value: T): void {\n this._store.set(value);\n }\n\n private _setAsync(value: Promise<T>): ReactPromise<boolean> {\n const promise = pending(value);\n this._pendingPromise = promise;\n return pending(this._store.setAsync(promise));\n }\n\n private _refetch(cacheStrategy: CacheStrategy): ReactPromise<T> {\n if (cacheStrategy === \"read-write\" && this._pendingPromise) {\n return this._pendingPromise;\n }\n const promise = pending(this._fetcher());\n if (cacheStrategy === \"never\") {\n return promise;\n }\n return pending(this._setAsync(promise).then(() => promise));\n }\n\n forceSetCachedValue(value: T): void {\n this._set(value);\n }\n\n forceSetCachedValueAsync(value: Promise<T>): ReactPromise<boolean> {\n return this._setAsync(value);\n }\n\n /**\n * Refetches the value from the fetcher, and updates the cache with it.\n */\n async refresh(): Promise<T> {\n return await this.getOrWait(\"write-only\");\n }\n\n /**\n * Invalidates the cache, marking it to refresh on the next read. If anyone was listening to it, it will refresh\n * immediately.\n */\n invalidate(): void {\n this._store.setUnavailable();\n this._pendingPromise = undefined;\n if (this._subscriptionsCount > 0) {\n runAsynchronously(this.refresh());\n }\n }\n\n onStateChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {\n const storeObj = this._store.onChange(callback);\n\n runAsynchronously(this.getOrWait(\"read-write\"));\n\n if (this._subscriptionsCount++ === 0 && this._options.onSubscribe) {\n const unsubscribe = this._options.onSubscribe(() => {\n runAsynchronously(this.refresh());\n });\n this._unsubscribers.push(unsubscribe);\n }\n\n let hasUnsubscribed = false;\n return {\n unsubscribe: () => {\n if (hasUnsubscribed) return;\n hasUnsubscribed = true;\n storeObj.unsubscribe();\n if (--this._subscriptionsCount === 0) {\n const currentRefreshPromiseIndex = ++this._mostRecentRefreshPromiseIndex;\n runAsynchronously(async () => {\n // wait a few seconds; if anything changes during that time, we don't want to refresh\n // else we do unnecessary requests if we unsubscribe and then subscribe again immediately\n await wait(5000);\n if (this._subscriptionsCount === 0 && currentRefreshPromiseIndex === this._mostRecentRefreshPromiseIndex) {\n this.invalidate();\n }\n });\n\n for (const unsubscribe of this._unsubscribers) {\n unsubscribe();\n }\n }\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AA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AAK,GAAI;AACf,gBAAI,KAAK,wBAAwB,KAAK,+BAA+B,KAAK,gCAAgC;AACxG,mBAAK,WAAW;AAAA,YAClB;AAAA,UACF,CAAC;AAED,qBAAW,eAAe,KAAK,gBAAgB;AAC7C,wBAAY;AAAA,UACd;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/utils/caches.tsx"],"sourcesContent":["import { DependenciesMap } from \"./maps\";\nimport { filterUndefined } from \"./objects\";\nimport { RateLimitOptions, ReactPromise, pending, rateLimited, resolved, runAsynchronously, wait } from \"./promises\";\nimport { AsyncStore } from \"./stores\";\n\n/**\n * Can be used to cache the result of a function call, for example for the `use` hook in React.\n */\nexport function cacheFunction<F extends Function>(f: F): F {\n const dependenciesMap = new DependenciesMap<any, any>();\n\n return ((...args: any) => {\n if (dependenciesMap.has(args)) {\n return dependenciesMap.get(args);\n }\n\n const value = f(...args);\n dependenciesMap.set(args, value);\n return value;\n }) as any as F;\n}\nundefined?.test(\"cacheFunction\", ({ expect }) => {\n // Test with a simple function\n let callCount = 0;\n const add = (a: number, b: number) => {\n callCount++;\n return a + b;\n };\n\n const cachedAdd = cacheFunction(add);\n\n // First call should execute the function\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Second call with same args should use cached result\n expect(cachedAdd(1, 2)).toBe(3);\n expect(callCount).toBe(1);\n\n // Call with different args should execute the function again\n expect(cachedAdd(2, 3)).toBe(5);\n expect(callCount).toBe(2);\n\n // Test with a function that returns objects\n let objectCallCount = 0;\n const createObject = (id: number) => {\n objectCallCount++;\n return { id };\n };\n\n const cachedCreateObject = cacheFunction(createObject);\n\n // First call should execute the function\n const obj1 = cachedCreateObject(1);\n expect(obj1).toEqual({ id: 1 });\n expect(objectCallCount).toBe(1);\n\n // Second call with same args should use cached result\n const obj2 = cachedCreateObject(1);\n expect(obj2).toBe(obj1); // Same reference\n expect(objectCallCount).toBe(1);\n});\n\n\ntype CacheStrategy = \"write-only\" | \"read-write\" | \"never\";\n\nexport class AsyncCache<D extends any[], T> {\n private readonly _map = new DependenciesMap<D, AsyncValueCache<T>>();\n\n constructor(\n private readonly _fetcher: (dependencies: D) => Promise<T>,\n private readonly _options: {\n onSubscribe?: (key: D, refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n // nothing here yet\n }\n\n private _createKeyed<FunctionName extends keyof AsyncValueCache<T>>(\n functionName: FunctionName,\n ): (key: D, ...args: Parameters<AsyncValueCache<T>[FunctionName]>) => ReturnType<AsyncValueCache<T>[FunctionName]> {\n return (key: D, ...args) => {\n const valueCache = this.getValueCache(key);\n return (valueCache[functionName] as any).apply(valueCache, args);\n };\n }\n\n getValueCache(dependencies: D): AsyncValueCache<T> {\n let cache = this._map.get(dependencies);\n if (!cache) {\n cache = new AsyncValueCache(\n async () => await this._fetcher(dependencies),\n {\n ...this._options,\n onSubscribe: this._options.onSubscribe ? (cb) => this._options.onSubscribe!(dependencies, cb) : undefined,\n },\n );\n this._map.set(dependencies, cache);\n }\n return cache;\n }\n\n async refreshWhere(predicate: (dependencies: D) => boolean) {\n const promises: Promise<T>[] = [];\n for (const [dependencies, cache] of this._map) {\n if (predicate(dependencies)) {\n promises.push(cache.refresh());\n }\n }\n await Promise.all(promises);\n }\n\n readonly isCacheAvailable = this._createKeyed(\"isCacheAvailable\");\n readonly getIfCached = this._createKeyed(\"getIfCached\");\n readonly getOrWait = this._createKeyed(\"getOrWait\");\n readonly forceSetCachedValue = this._createKeyed(\"forceSetCachedValue\");\n readonly forceSetCachedValueAsync = this._createKeyed(\"forceSetCachedValueAsync\");\n readonly refresh = this._createKeyed(\"refresh\");\n readonly invalidate = this._createKeyed(\"invalidate\");\n readonly onStateChange = this._createKeyed(\"onStateChange\");\n readonly isDirty = this._createKeyed(\"isDirty\");\n}\n\nclass AsyncValueCache<T> {\n private _store: AsyncStore<T>;\n private _pendingPromise: ReactPromise<T> | undefined;\n private _fetcher: () => Promise<T>;\n private readonly _rateLimitOptions: Omit<RateLimitOptions, \"batchCalls\">;\n private _subscriptionsCount = 0;\n private _unsubscribers: (() => void)[] = [];\n private _mostRecentRefreshPromiseIndex = 0;\n\n constructor(\n fetcher: () => Promise<T>,\n private readonly _options: {\n onSubscribe?: (refresh: () => void) => (() => void),\n rateLimiter?: Omit<RateLimitOptions, \"batchCalls\">,\n } = {},\n ) {\n this._store = new AsyncStore();\n this._rateLimitOptions = {\n concurrency: 1,\n throttleMs: 300,\n ...filterUndefined(_options.rateLimiter ?? {}),\n };\n\n\n this._fetcher = rateLimited(fetcher, {\n ...this._rateLimitOptions,\n batchCalls: true,\n });\n }\n\n isCacheAvailable(): boolean {\n return this._store.isAvailable();\n }\n\n getIfCached() {\n return this._store.get();\n }\n\n getOrWait(cacheStrategy: CacheStrategy): ReactPromise<T> {\n const cached = this.getIfCached();\n if (cacheStrategy === \"read-write\" && cached.status === \"ok\") {\n return resolved(cached.data);\n }\n\n return this._refetch(cacheStrategy);\n }\n\n private _set(value: T): void {\n this._store.set(value);\n }\n\n private _setAsync(value: Promise<T>): ReactPromise<boolean> {\n const promise = pending(value);\n this._pendingPromise = promise;\n return pending(this._store.setAsync(promise));\n }\n\n private _refetch(cacheStrategy: CacheStrategy): ReactPromise<T> {\n if (cacheStrategy === \"read-write\" && this._pendingPromise) {\n return this._pendingPromise;\n }\n const promise = pending(this._fetcher());\n if (cacheStrategy === \"never\") {\n return promise;\n }\n return pending(this._setAsync(promise).then(() => promise));\n }\n\n forceSetCachedValue(value: T): void {\n this._set(value);\n }\n\n forceSetCachedValueAsync(value: Promise<T>): ReactPromise<boolean> {\n return this._setAsync(value);\n }\n\n /**\n * Refetches the value from the fetcher, and updates the cache with it.\n */\n async refresh(): Promise<T> {\n return await this.getOrWait(\"write-only\");\n }\n\n /**\n * Invalidates the cache, marking it dirty (ie. it will be refreshed on the next read). If anyone was listening to it,\n * it will refresh immediately.\n */\n invalidate(): void {\n this._store.setUnavailable();\n this._pendingPromise = undefined;\n if (this._subscriptionsCount > 0) {\n runAsynchronously(this.refresh());\n }\n }\n\n isDirty(): boolean {\n return this._pendingPromise === undefined;\n }\n\n onStateChange(callback: (value: T, oldValue: T | undefined) => void): { unsubscribe: () => void } {\n const storeObj = this._store.onChange(callback);\n\n runAsynchronously(this.getOrWait(\"read-write\"));\n\n if (this._subscriptionsCount++ === 0 && this._options.onSubscribe) {\n const unsubscribe = this._options.onSubscribe(() => {\n runAsynchronously(this.refresh());\n });\n this._unsubscribers.push(unsubscribe);\n }\n\n let hasUnsubscribed = false;\n return {\n unsubscribe: () => {\n if (hasUnsubscribed) return;\n hasUnsubscribed = true;\n storeObj.unsubscribe();\n if (--this._subscriptionsCount === 0) {\n const currentRefreshPromiseIndex = ++this._mostRecentRefreshPromiseIndex;\n runAsynchronously(async () => {\n // wait a few seconds; if anything changes during that time, we don't want to refresh\n // else we do unnecessary requests if we unsubscribe and then subscribe again immediately\n await wait(5000);\n if (this._subscriptionsCount === 0 && currentRefreshPromiseIndex === this._mostRecentRefreshPromiseIndex) {\n this.invalidate();\n }\n });\n\n for (const unsubscribe of this._unsubscribers) {\n unsubscribe();\n }\n }\n },\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAgC;AAChC,qBAAgC;AAChC,sBAAwG;AACxG,oBAA2B;AAKpB,SAAS,cAAkC,GAAS;AACzD,QAAM,kBAAkB,IAAI,4BAA0B;AAEtD,SAAQ,IAAI,SAAc;AACxB,QAAI,gBAAgB,IAAI,IAAI,GAAG;AAC7B,aAAO,gBAAgB,IAAI,IAAI;AAAA,IACjC;AAEA,UAAM,QAAQ,EAAE,GAAG,IAAI;AACvB,oBAAgB,IAAI,MAAM,KAAK;AAC/B,WAAO;AAAA,EACT;AACF;AA8CO,IAAM,aAAN,MAAqC;AAAA,EAG1C,YACmB,UACA,WAGb,CAAC,GACL;AALiB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yB,OAA0C;AACjE,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,UAAsB;AAC1B,WAAO,MAAM,KAAK,UAAU,YAAY;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAmB;AACjB,SAAK,OAAO,eAAe;AAC3B,SAAK,kBAAkB;AACvB,QAAI,KAAK,sBAAsB,GAAG;AAChC,6CAAkB,KAAK,QAAQ,CAAC;AAAA,IAClC;AAAA,EACF;AAAA,EAEA,UAAmB;AACjB,WAAO,KAAK,oBAAoB;AAAA,EAClC;AAAA,EAEA,cAAc,UAAoF;AAChG,UAAM,WAAW,KAAK,OAAO,SAAS,QAAQ;AAE9C,2CAAkB,KAAK,UAAU,YAAY,CAAC;AAE9C,QAAI,KAAK,0BAA0B,KAAK,KAAK,SAAS,aAAa;AACjE,YAAM,cAAc,KAAK,SAAS,YAAY,MAAM;AAClD,+CAAkB,KAAK,QAAQ,CAAC;AAAA,MAClC,CAAC;AACD,WAAK,eAAe,KAAK,WAAW;AAAA,IACtC;AAEA,QAAI,kBAAkB;AACtB,WAAO;AAAA,MACL,aAAa,MAAM;AACjB,YAAI,gBAAiB;AACrB,0BAAkB;AAClB,iBAAS,YAAY;AACrB,YAAI,EAAE,KAAK,wBAAwB,GAAG;AACpC,gBAAM,6BAA6B,EAAE,KAAK;AAC1C,iDAAkB,YAAY;AAG5B,sBAAM,sBAAK,GAAI;AACf,gBAAI,KAAK,wBAAwB,KAAK,+BAA+B,KAAK,gCAAgC;AACxG,mBAAK,WAAW;AAAA,YAClB;AAAA,UACF,CAAC;AAED,qBAAW,eAAe,KAAK,gBAAgB;AAC7C,wBAAY;AAAA,UACd;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1,5 +1,7 @@
1
1
  declare const globalVar: any;
2
2
 
3
3
  declare function createGlobal<T>(key: string, init: () => T): T;
4
+ declare function getGlobal(key: string): any;
5
+ declare function setGlobal(key: string, value: any): void;
4
6
 
5
- export { createGlobal, globalVar };
7
+ export { createGlobal, getGlobal, globalVar, setGlobal };
@@ -1,5 +1,7 @@
1
1
  declare const globalVar: any;
2
2
 
3
3
  declare function createGlobal<T>(key: string, init: () => T): T;
4
+ declare function getGlobal(key: string): any;
5
+ declare function setGlobal(key: string, value: any): void;
4
6
 
5
- export { createGlobal, globalVar };
7
+ export { createGlobal, getGlobal, globalVar, setGlobal };
@@ -21,7 +21,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var globals_exports = {};
22
22
  __export(globals_exports, {
23
23
  createGlobal: () => createGlobal,
24
- globalVar: () => globalVar
24
+ getGlobal: () => getGlobal,
25
+ globalVar: () => globalVar,
26
+ setGlobal: () => setGlobal
25
27
  });
26
28
  module.exports = __toCommonJS(globals_exports);
27
29
  var globalVar = typeof globalThis !== "undefined" ? globalThis : typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {};
@@ -36,9 +38,17 @@ function createGlobal(key, init) {
36
38
  }
37
39
  return globalVar[stackGlobalsSymbol][key];
38
40
  }
41
+ function getGlobal(key) {
42
+ return globalVar[stackGlobalsSymbol][key];
43
+ }
44
+ function setGlobal(key, value) {
45
+ globalVar[stackGlobalsSymbol][key] = value;
46
+ }
39
47
  // Annotate the CommonJS export names for ESM import in node:
40
48
  0 && (module.exports = {
41
49
  createGlobal,
42
- globalVar
50
+ getGlobal,
51
+ globalVar,
52
+ setGlobal
43
53
  });
44
54
  //# sourceMappingURL=globals.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/globals.tsx"],"sourcesContent":["const globalVar: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof global !== 'undefined' ? global :\n typeof window !== 'undefined' ? window :\n typeof self !== 'undefined' ? self :\n {};\nexport {\n globalVar\n};\n\nif (typeof globalThis === 'undefined') {\n (globalVar as any).globalThis = globalVar;\n}\n\nconst stackGlobalsSymbol = Symbol.for('__stack-globals');\nglobalVar[stackGlobalsSymbol] ??= {};\n\nexport function createGlobal<T>(key: string, init: () => T) {\n if (!globalVar[stackGlobalsSymbol][key]) {\n globalVar[stackGlobalsSymbol][key] = init();\n }\n return globalVar[stackGlobalsSymbol][key] as T;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAM,YACJ,OAAO,eAAe,cAAc,aAClC,OAAO,WAAW,cAAc,SAC9B,OAAO,WAAW,cAAc,SAC9B,OAAO,SAAS,cAAc,OAC5B,CAAC;AAKX,IAAI,OAAO,eAAe,aAAa;AACrC,EAAC,UAAkB,aAAa;AAClC;AAEA,IAAM,qBAAqB,OAAO,IAAI,iBAAiB;AACvD,UAAU,kBAAkB,MAAM,CAAC;AAE5B,SAAS,aAAgB,KAAa,MAAe;AAC1D,MAAI,CAAC,UAAU,kBAAkB,EAAE,GAAG,GAAG;AACvC,cAAU,kBAAkB,EAAE,GAAG,IAAI,KAAK;AAAA,EAC5C;AACA,SAAO,UAAU,kBAAkB,EAAE,GAAG;AAC1C;","names":[]}
1
+ {"version":3,"sources":["../../src/utils/globals.tsx"],"sourcesContent":["const globalVar: any =\n typeof globalThis !== 'undefined' ? globalThis :\n typeof global !== 'undefined' ? global :\n typeof window !== 'undefined' ? window :\n typeof self !== 'undefined' ? self :\n {};\nexport {\n globalVar\n};\n\nif (typeof globalThis === 'undefined') {\n (globalVar as any).globalThis = globalVar;\n}\n\nconst stackGlobalsSymbol = Symbol.for('__stack-globals');\nglobalVar[stackGlobalsSymbol] ??= {};\n\nexport function createGlobal<T>(key: string, init: () => T) {\n if (!globalVar[stackGlobalsSymbol][key]) {\n globalVar[stackGlobalsSymbol][key] = init();\n }\n return globalVar[stackGlobalsSymbol][key] as T;\n}\n\nexport function getGlobal(key: string): any {\n return globalVar[stackGlobalsSymbol][key];\n}\n\nexport function setGlobal(key: string, value: any) {\n globalVar[stackGlobalsSymbol][key] = value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAM,YACJ,OAAO,eAAe,cAAc,aAClC,OAAO,WAAW,cAAc,SAC9B,OAAO,WAAW,cAAc,SAC9B,OAAO,SAAS,cAAc,OAC5B,CAAC;AAKX,IAAI,OAAO,eAAe,aAAa;AACrC,EAAC,UAAkB,aAAa;AAClC;AAEA,IAAM,qBAAqB,OAAO,IAAI,iBAAiB;AACvD,UAAU,kBAAkB,MAAM,CAAC;AAE5B,SAAS,aAAgB,KAAa,MAAe;AAC1D,MAAI,CAAC,UAAU,kBAAkB,EAAE,GAAG,GAAG;AACvC,cAAU,kBAAkB,EAAE,GAAG,IAAI,KAAK;AAAA,EAC5C;AACA,SAAO,UAAU,kBAAkB,EAAE,GAAG;AAC1C;AAEO,SAAS,UAAU,KAAkB;AAC1C,SAAO,UAAU,kBAAkB,EAAE,GAAG;AAC1C;AAEO,SAAS,UAAU,KAAa,OAAY;AACjD,YAAU,kBAAkB,EAAE,GAAG,IAAI;AACvC;","names":[]}
@@ -40,6 +40,7 @@ type RefState<T> = ReadonlyRef<T> & {
40
40
  */
41
41
  declare function useRefState<T>(initialValue: T): RefState<T>;
42
42
  declare function mapRefState<T, R>(refState: RefState<T>, mapper: (value: T) => R, reverseMapper: (oldT: T, newR: R) => T): RefState<R>;
43
+ declare function shouldRethrowRenderingError(error: unknown): boolean;
43
44
  declare class NoSuspenseBoundaryError extends Error {
44
45
  digest: string;
45
46
  reason: string;
@@ -52,4 +53,4 @@ declare class NoSuspenseBoundaryError extends Error {
52
53
  */
53
54
  declare function suspendIfSsr(caller?: string): void;
54
55
 
55
- export { NoSuspenseBoundaryError, type ReadonlyRef, type RefState, componentWrapper, forwardRefIfNeeded, getNodeText, mapRef, mapRefState, suspend, suspendIfSsr, useRefState };
56
+ export { NoSuspenseBoundaryError, type ReadonlyRef, type RefState, componentWrapper, forwardRefIfNeeded, getNodeText, mapRef, mapRefState, shouldRethrowRenderingError, suspend, suspendIfSsr, useRefState };
@@ -40,6 +40,7 @@ type RefState<T> = ReadonlyRef<T> & {
40
40
  */
41
41
  declare function useRefState<T>(initialValue: T): RefState<T>;
42
42
  declare function mapRefState<T, R>(refState: RefState<T>, mapper: (value: T) => R, reverseMapper: (oldT: T, newR: R) => T): RefState<R>;
43
+ declare function shouldRethrowRenderingError(error: unknown): boolean;
43
44
  declare class NoSuspenseBoundaryError extends Error {
44
45
  digest: string;
45
46
  reason: string;
@@ -52,4 +53,4 @@ declare class NoSuspenseBoundaryError extends Error {
52
53
  */
53
54
  declare function suspendIfSsr(caller?: string): void;
54
55
 
55
- export { NoSuspenseBoundaryError, type ReadonlyRef, type RefState, componentWrapper, forwardRefIfNeeded, getNodeText, mapRef, mapRefState, suspend, suspendIfSsr, useRefState };
56
+ export { NoSuspenseBoundaryError, type ReadonlyRef, type RefState, componentWrapper, forwardRefIfNeeded, getNodeText, mapRef, mapRefState, shouldRethrowRenderingError, suspend, suspendIfSsr, useRefState };
@@ -36,6 +36,7 @@ __export(react_exports, {
36
36
  getNodeText: () => getNodeText,
37
37
  mapRef: () => mapRef,
38
38
  mapRefState: () => mapRefState,
39
+ shouldRethrowRenderingError: () => shouldRethrowRenderingError,
39
40
  suspend: () => suspend,
40
41
  suspendIfSsr: () => suspendIfSsr,
41
42
  useRefState: () => useRefState
@@ -95,9 +96,7 @@ function useRefState(initialValue) {
95
96
  const ref = import_react.default.useRef(initialValue);
96
97
  const setValue = import_react.default.useCallback((updater) => {
97
98
  const value = typeof updater === "function" ? updater(ref.current) : updater;
98
- console.log("setValue", ref.current);
99
99
  ref.current = value;
100
- console.log("setValue", ref.current);
101
100
  setState(value);
102
101
  }, []);
103
102
  const res = import_react.default.useMemo(() => ({
@@ -124,16 +123,23 @@ function mapRefState(refState, mapper, reverseMapper) {
124
123
  }
125
124
  };
126
125
  }
126
+ function shouldRethrowRenderingError(error) {
127
+ return !!error && typeof error === "object" && "digest" in error && error.digest === "BAILOUT_TO_CLIENT_SIDE_RENDERING";
128
+ }
127
129
  var NoSuspenseBoundaryError = class extends Error {
128
130
  constructor(options) {
129
131
  super(import_strings.deindent`
132
+ Suspense boundary not found! Read the error message below carefully on how to fix it.
133
+
130
134
  ${options.caller ?? "This code path"} attempted to display a loading indicator, but didn't find a Suspense boundary above it. Please read the error message below carefully.
131
135
 
132
- The fix depends on which of the 3 scenarios caused it:
136
+ The fix depends on which of the 4 scenarios caused it:
133
137
 
134
- 1. You are missing a loading.tsx file in your app directory. Fix it by adding a loading.tsx file in your app directory.
138
+ 1. [Next.js] You are missing a loading.tsx file in your app directory. Fix it by adding a loading.tsx file in your app directory.
139
+
140
+ 2. [React] You are missing a <Suspense> boundary in your component. Fix it by wrapping your component (or the entire app) in a <Suspense> component.
135
141
 
136
- 2. The component is rendered in the root (outermost) layout.tsx or template.tsx file. Next.js does not wrap those files in a Suspense boundary, even if there is a loading.tsx file in the same folder. To fix it, wrap your layout inside a route group like this:
142
+ 3. [Next.js] The component is rendered in the root (outermost) layout.tsx or template.tsx file. Next.js does not wrap those files in a Suspense boundary, even if there is a loading.tsx file in the same folder. To fix it, wrap your layout inside a route group like this:
137
143
 
138
144
  - app
139
145
  - - layout.tsx // contains <html> and <body>, alongside providers and other components that don't need ${options.caller ?? "this code path"}
@@ -145,7 +151,7 @@ var NoSuspenseBoundaryError = class extends Error {
145
151
 
146
152
  For more information on this approach, see Next's documentation on route groups: https://nextjs.org/docs/app/building-your-application/routing/route-groups
147
153
 
148
- 3. You caught this error with try-catch or a custom error boundary. Fix this by rethrowing the error or not catching it in the first place.
154
+ 4. You caught this error with try-catch or a custom error boundary. Fix this by rethrowing the error or not catching it in the first place.
149
155
 
150
156
  See: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout
151
157
 
@@ -169,6 +175,7 @@ function suspendIfSsr(caller) {
169
175
  getNodeText,
170
176
  mapRef,
171
177
  mapRefState,
178
+ shouldRethrowRenderingError,
172
179
  suspend,
173
180
  suspendIfSsr,
174
181
  useRefState
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/react.tsx"],"sourcesContent":["import React, { SetStateAction } from \"react\";\nimport { isBrowserLike } from \"./env\";\nimport { neverResolve } from \"./promises\";\nimport { deindent } from \"./strings\";\n\nexport function componentWrapper<\n C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements,\n ExtraProps extends {} = {}\n>(displayName: string, render: React.ForwardRefRenderFunction<RefFromComponent<C>, React.ComponentPropsWithRef<C> & ExtraProps>) {\n const Component = forwardRefIfNeeded(render);\n Component.displayName = displayName;\n return Component;\n}\ntype RefFromComponent<C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements> = NonNullable<RefFromComponentDistCond<React.ComponentPropsWithRef<C>[\"ref\"]>>;\ntype RefFromComponentDistCond<A> = A extends React.RefObject<infer T> ? T : never; // distributive conditional type; see https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types\n\nexport function forwardRefIfNeeded<T, P = {}>(render: React.ForwardRefRenderFunction<T, P>): React.FC<P & { ref?: React.Ref<T> }> {\n // TODO: when we drop support for react 18, remove this\n\n const version = React.version;\n const major = parseInt(version.split(\".\")[0]);\n if (major < 19) {\n return React.forwardRef<T, P>(render as any) as any;\n } else {\n return ((props: P) => render(props, (props as any).ref)) as any;\n }\n}\n\nexport function getNodeText(node: React.ReactNode): string {\n if ([\"number\", \"string\"].includes(typeof node)) {\n return `${node}`;\n }\n if (!node) {\n return \"\";\n }\n if (Array.isArray(node)) {\n return node.map(getNodeText).join(\"\");\n }\n if (typeof node === \"object\" && \"props\" in node) {\n return getNodeText(node.props.children);\n }\n throw new Error(`Unknown node type: ${typeof node}`);\n}\nundefined?.test(\"getNodeText\", ({ expect }) => {\n // Test with string\n expect(getNodeText(\"hello\")).toBe(\"hello\");\n\n // Test with number\n expect(getNodeText(42)).toBe(\"42\");\n\n // Test with null/undefined\n expect(getNodeText(null)).toBe(\"\");\n expect(getNodeText(undefined)).toBe(\"\");\n\n // Test with array\n expect(getNodeText([\"hello\", \" \", \"world\"])).toBe(\"hello world\");\n expect(getNodeText([1, 2, 3])).toBe(\"123\");\n\n // Test with mixed array\n expect(getNodeText([\"hello\", 42, null])).toBe(\"hello42\");\n\n // Test with React element (mocked)\n const mockElement = {\n props: {\n children: \"child text\"\n }\n } as React.ReactElement;\n expect(getNodeText(mockElement)).toBe(\"child text\");\n\n // Test with nested React elements\n const nestedElement = {\n props: {\n children: {\n props: {\n children: \"nested text\"\n }\n } as React.ReactElement\n }\n } as React.ReactElement;\n expect(getNodeText(nestedElement)).toBe(\"nested text\");\n\n // Test with array of React elements\n const arrayOfElements = [\n { props: { children: \"first\" } } as React.ReactElement,\n { props: { children: \"second\" } } as React.ReactElement\n ];\n expect(getNodeText(arrayOfElements)).toBe(\"firstsecond\");\n});\n\n/**\n * Suspends the currently rendered component indefinitely. Will not unsuspend unless the component rerenders.\n *\n * You can use this to translate older query- or AsyncResult-based code to new the Suspense system, for example: `if (query.isLoading) suspend();`\n */\nexport function suspend(): never {\n React.use(neverResolve());\n throw new Error(\"Somehow a Promise that never resolves was resolved?\");\n}\n\nexport function mapRef<T, R>(ref: ReadonlyRef<T>, mapper: (value: T) => R): ReadonlyRef<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = ref.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n };\n}\n\nexport type ReadonlyRef<T> = {\n readonly current: T,\n};\n\nexport type RefState<T> = ReadonlyRef<T> & {\n set: (updater: SetStateAction<T>) => void,\n};\n\n/**\n * Like useState, but its value is immediately available on refState.current after being set.\n *\n * Like useRef, but setting the value will cause a rerender.\n *\n * Note that useRefState returns a new object every time a rerender happens due to a value change, which is intentional\n * as it allows you to specify it in a dependency array like this:\n *\n * ```tsx\n * useEffect(() => {\n * // do something with refState.current\n * }, [refState]); // instead of refState.current\n * ```\n *\n * If you don't want this, you can wrap the result in a useMemo call.\n */\nexport function useRefState<T>(initialValue: T): RefState<T> {\n const [, setState] = React.useState(initialValue);\n const ref = React.useRef(initialValue);\n const setValue = React.useCallback((updater: SetStateAction<T>) => {\n const value: T = typeof updater === \"function\" ? (updater as any)(ref.current) : updater;\n console.log(\"setValue\", ref.current);\n ref.current = value;\n console.log(\"setValue\", ref.current);\n setState(value);\n }, []);\n const res = React.useMemo(() => ({\n get current() {\n return ref.current;\n },\n set: setValue,\n }), [setValue]);\n return res;\n}\n\nexport function mapRefState<T, R>(refState: RefState<T>, mapper: (value: T) => R, reverseMapper: (oldT: T, newR: R) => T): RefState<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = refState.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n set(updater: SetStateAction<R>) {\n const value: R = typeof updater === \"function\" ? (updater as any)(this.current) : updater;\n refState.set(reverseMapper(refState.current, value));\n },\n };\n}\n\nexport class NoSuspenseBoundaryError extends Error {\n digest: string;\n reason: string;\n\n constructor(options: { caller?: string }) {\n super(deindent`\n ${options.caller ?? \"This code path\"} attempted to display a loading indicator, but didn't find a Suspense boundary above it. Please read the error message below carefully.\n \n The fix depends on which of the 3 scenarios caused it:\n \n 1. You are missing a loading.tsx file in your app directory. Fix it by adding a loading.tsx file in your app directory.\n\n 2. The component is rendered in the root (outermost) layout.tsx or template.tsx file. Next.js does not wrap those files in a Suspense boundary, even if there is a loading.tsx file in the same folder. To fix it, wrap your layout inside a route group like this:\n\n - app\n - - layout.tsx // contains <html> and <body>, alongside providers and other components that don't need ${options.caller ?? \"this code path\"}\n - - loading.tsx // required for suspense\n - - (main)\n - - - layout.tsx // contains the main layout of your app, like a sidebar or a header, and can use ${options.caller ?? \"this code path\"}\n - - - route.tsx // your actual main page\n - - - the rest of your app\n\n For more information on this approach, see Next's documentation on route groups: https://nextjs.org/docs/app/building-your-application/routing/route-groups\n \n 3. You caught this error with try-catch or a custom error boundary. Fix this by rethrowing the error or not catching it in the first place.\n\n See: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n\n More information on SSR and Suspense boundaries: https://react.dev/reference/react/Suspense#providing-a-fallback-for-server-errors-and-client-only-content\n `);\n\n this.name = \"NoSuspenseBoundaryError\";\n this.reason = options.caller ?? \"suspendIfSsr()\";\n\n // set the digest so nextjs doesn't log the error\n // https://github.com/vercel/next.js/blob/d01d6d9c35a8c2725b3d74c1402ab76d4779a6cf/packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts#L14\n this.digest = \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n }\n}\nundefined?.test(\"NoSuspenseBoundaryError\", ({ expect }) => {\n // Test with default options\n const defaultError = new NoSuspenseBoundaryError({});\n expect(defaultError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(defaultError.reason).toBe(\"suspendIfSsr()\");\n expect(defaultError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(defaultError.message).toContain(\"This code path attempted to display a loading indicator\");\n\n // Test with custom caller\n const customError = new NoSuspenseBoundaryError({ caller: \"CustomComponent\" });\n expect(customError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(customError.reason).toBe(\"CustomComponent\");\n expect(customError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(customError.message).toContain(\"CustomComponent attempted to display a loading indicator\");\n\n // Verify error message contains all the necessary information\n expect(customError.message).toContain(\"loading.tsx\");\n expect(customError.message).toContain(\"route groups\");\n expect(customError.message).toContain(\"https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\");\n});\n\n\n/**\n * Use this in a component or a hook to disable SSR. Should be wrapped in a Suspense boundary, or it will throw an error.\n */\nexport function suspendIfSsr(caller?: string) {\n if (!isBrowserLike()) {\n throw new NoSuspenseBoundaryError({ caller });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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A;AAAA;AAAA;AAAA;AAAA;AAAA,KAW1I;AAED,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ,UAAU;AAIhC,SAAK,SAAS;AAAA,EAChB;AACF;AA0BO,SAAS,aAAa,QAAiB;AAC5C,MAAI,KAAC,0BAAc,GAAG;AACpB,UAAM,IAAI,wBAAwB,EAAE,OAAO,CAAC;AAAA,EAC9C;AACF;","names":["React"]}
1
+ {"version":3,"sources":["../../src/utils/react.tsx"],"sourcesContent":["import React, { SetStateAction } from \"react\";\nimport { isBrowserLike } from \"./env\";\nimport { neverResolve } from \"./promises\";\nimport { deindent } from \"./strings\";\n\nexport function componentWrapper<\n C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements,\n ExtraProps extends {} = {}\n>(displayName: string, render: React.ForwardRefRenderFunction<RefFromComponent<C>, React.ComponentPropsWithRef<C> & ExtraProps>) {\n const Component = forwardRefIfNeeded(render);\n Component.displayName = displayName;\n return Component;\n}\ntype RefFromComponent<C extends React.ComponentType<any> | keyof React.JSX.IntrinsicElements> = NonNullable<RefFromComponentDistCond<React.ComponentPropsWithRef<C>[\"ref\"]>>;\ntype RefFromComponentDistCond<A> = A extends React.RefObject<infer T> ? T : never; // distributive conditional type; see https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types\n\nexport function forwardRefIfNeeded<T, P = {}>(render: React.ForwardRefRenderFunction<T, P>): React.FC<P & { ref?: React.Ref<T> }> {\n // TODO: when we drop support for react 18, remove this\n\n const version = React.version;\n const major = parseInt(version.split(\".\")[0]);\n if (major < 19) {\n return React.forwardRef<T, P>(render as any) as any;\n } else {\n return ((props: P) => render(props, (props as any).ref)) as any;\n }\n}\n\nexport function getNodeText(node: React.ReactNode): string {\n if ([\"number\", \"string\"].includes(typeof node)) {\n return `${node}`;\n }\n if (!node) {\n return \"\";\n }\n if (Array.isArray(node)) {\n return node.map(getNodeText).join(\"\");\n }\n if (typeof node === \"object\" && \"props\" in node) {\n return getNodeText(node.props.children);\n }\n throw new Error(`Unknown node type: ${typeof node}`);\n}\nundefined?.test(\"getNodeText\", ({ expect }) => {\n // Test with string\n expect(getNodeText(\"hello\")).toBe(\"hello\");\n\n // Test with number\n expect(getNodeText(42)).toBe(\"42\");\n\n // Test with null/undefined\n expect(getNodeText(null)).toBe(\"\");\n expect(getNodeText(undefined)).toBe(\"\");\n\n // Test with array\n expect(getNodeText([\"hello\", \" \", \"world\"])).toBe(\"hello world\");\n expect(getNodeText([1, 2, 3])).toBe(\"123\");\n\n // Test with mixed array\n expect(getNodeText([\"hello\", 42, null])).toBe(\"hello42\");\n\n // Test with React element (mocked)\n const mockElement = {\n props: {\n children: \"child text\"\n }\n } as React.ReactElement;\n expect(getNodeText(mockElement)).toBe(\"child text\");\n\n // Test with nested React elements\n const nestedElement = {\n props: {\n children: {\n props: {\n children: \"nested text\"\n }\n } as React.ReactElement\n }\n } as React.ReactElement;\n expect(getNodeText(nestedElement)).toBe(\"nested text\");\n\n // Test with array of React elements\n const arrayOfElements = [\n { props: { children: \"first\" } } as React.ReactElement,\n { props: { children: \"second\" } } as React.ReactElement\n ];\n expect(getNodeText(arrayOfElements)).toBe(\"firstsecond\");\n});\n\n/**\n * Suspends the currently rendered component indefinitely. Will not unsuspend unless the component rerenders.\n *\n * You can use this to translate older query- or AsyncResult-based code to new the Suspense system, for example: `if (query.isLoading) suspend();`\n */\nexport function suspend(): never {\n React.use(neverResolve());\n throw new Error(\"Somehow a Promise that never resolves was resolved?\");\n}\n\nexport function mapRef<T, R>(ref: ReadonlyRef<T>, mapper: (value: T) => R): ReadonlyRef<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = ref.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n };\n}\n\nexport type ReadonlyRef<T> = {\n readonly current: T,\n};\n\nexport type RefState<T> = ReadonlyRef<T> & {\n set: (updater: SetStateAction<T>) => void,\n};\n\n/**\n * Like useState, but its value is immediately available on refState.current after being set.\n *\n * Like useRef, but setting the value will cause a rerender.\n *\n * Note that useRefState returns a new object every time a rerender happens due to a value change, which is intentional\n * as it allows you to specify it in a dependency array like this:\n *\n * ```tsx\n * useEffect(() => {\n * // do something with refState.current\n * }, [refState]); // instead of refState.current\n * ```\n *\n * If you don't want this, you can wrap the result in a useMemo call.\n */\nexport function useRefState<T>(initialValue: T): RefState<T> {\n const [, setState] = React.useState(initialValue);\n const ref = React.useRef(initialValue);\n const setValue = React.useCallback((updater: SetStateAction<T>) => {\n const value: T = typeof updater === \"function\" ? (updater as any)(ref.current) : updater;\n ref.current = value;\n setState(value);\n }, []);\n const res = React.useMemo(() => ({\n get current() {\n return ref.current;\n },\n set: setValue,\n }), [setValue]);\n return res;\n}\n\nexport function mapRefState<T, R>(refState: RefState<T>, mapper: (value: T) => R, reverseMapper: (oldT: T, newR: R) => T): RefState<R> {\n let last: [T, R] | null = null;\n return {\n get current() {\n const input = refState.current;\n if (last === null || input !== last[0]) {\n last = [input, mapper(input)];\n }\n return last[1];\n },\n set(updater: SetStateAction<R>) {\n const value: R = typeof updater === \"function\" ? (updater as any)(this.current) : updater;\n refState.set(reverseMapper(refState.current, value));\n },\n };\n}\n\nexport function shouldRethrowRenderingError(error: unknown): boolean {\n return !!error && typeof error === \"object\" && \"digest\" in error && error.digest === \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n}\n\nexport class NoSuspenseBoundaryError extends Error {\n digest: string;\n reason: string;\n\n constructor(options: { caller?: string }) {\n super(deindent`\n Suspense boundary not found! Read the error message below carefully on how to fix it.\n\n ${options.caller ?? \"This code path\"} attempted to display a loading indicator, but didn't find a Suspense boundary above it. Please read the error message below carefully.\n \n The fix depends on which of the 4 scenarios caused it:\n \n 1. [Next.js] You are missing a loading.tsx file in your app directory. Fix it by adding a loading.tsx file in your app directory.\n\n 2. [React] You are missing a <Suspense> boundary in your component. Fix it by wrapping your component (or the entire app) in a <Suspense> component.\n\n 3. [Next.js] The component is rendered in the root (outermost) layout.tsx or template.tsx file. Next.js does not wrap those files in a Suspense boundary, even if there is a loading.tsx file in the same folder. To fix it, wrap your layout inside a route group like this:\n\n - app\n - - layout.tsx // contains <html> and <body>, alongside providers and other components that don't need ${options.caller ?? \"this code path\"}\n - - loading.tsx // required for suspense\n - - (main)\n - - - layout.tsx // contains the main layout of your app, like a sidebar or a header, and can use ${options.caller ?? \"this code path\"}\n - - - route.tsx // your actual main page\n - - - the rest of your app\n\n For more information on this approach, see Next's documentation on route groups: https://nextjs.org/docs/app/building-your-application/routing/route-groups\n \n 4. You caught this error with try-catch or a custom error boundary. Fix this by rethrowing the error or not catching it in the first place.\n\n See: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n\n More information on SSR and Suspense boundaries: https://react.dev/reference/react/Suspense#providing-a-fallback-for-server-errors-and-client-only-content\n `);\n\n this.name = \"NoSuspenseBoundaryError\";\n this.reason = options.caller ?? \"suspendIfSsr()\";\n\n // set the digest so nextjs doesn't log the error\n // https://github.com/vercel/next.js/blob/d01d6d9c35a8c2725b3d74c1402ab76d4779a6cf/packages/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts#L14\n this.digest = \"BAILOUT_TO_CLIENT_SIDE_RENDERING\";\n }\n}\nundefined?.test(\"NoSuspenseBoundaryError\", ({ expect }) => {\n // Test with default options\n const defaultError = new NoSuspenseBoundaryError({});\n expect(defaultError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(defaultError.reason).toBe(\"suspendIfSsr()\");\n expect(defaultError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(defaultError.message).toContain(\"This code path attempted to display a loading indicator\");\n\n // Test with custom caller\n const customError = new NoSuspenseBoundaryError({ caller: \"CustomComponent\" });\n expect(customError.name).toBe(\"NoSuspenseBoundaryError\");\n expect(customError.reason).toBe(\"CustomComponent\");\n expect(customError.digest).toBe(\"BAILOUT_TO_CLIENT_SIDE_RENDERING\");\n expect(customError.message).toContain(\"CustomComponent attempted to display a loading indicator\");\n\n // Verify error message contains all the necessary information\n expect(customError.message).toContain(\"loading.tsx\");\n expect(customError.message).toContain(\"route groups\");\n expect(customError.message).toContain(\"https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\");\n});\n\n\n/**\n * Use this in a component or a hook to disable SSR. Should be wrapped in a Suspense boundary, or it will throw an error.\n */\nexport function suspendIfSsr(caller?: string) {\n if (!isBrowserLike()) {\n throw new NoSuspenseBoundaryError({ caller });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAsC;AACtC,iBAA8B;AAC9B,sBAA6B;AAC7B,qBAAyB;AAElB,SAAS,iBAGd,aAAqB,QAA0G;AAC/H,QAAM,YAAY,mBAAmB,MAAM;AAC3C,YAAU,cAAc;AACxB,SAAO;AACT;AAIO,SAAS,mBAA8B,QAAoF;AAGhI,QAAM,UAAU,aAAAA,QAAM;AACtB,QAAM,QAAQ,SAAS,QAAQ,MAAM,GAAG,EAAE,CAAC,CAAC;AAC5C,MAAI,QAAQ,IAAI;AACd,WAAO,aAAAA,QAAM,WAAiB,MAAa;AAAA,EAC7C,OAAO;AACL,WAAQ,CAAC,UAAa,OAAO,OAAQ,MAAc,GAAG;AAAA,EACxD;AACF;AAEO,SAAS,YAAY,MAA+B;AACzD,MAAI,CAAC,UAAU,QAAQ,EAAE,SAAS,OAAO,IAAI,GAAG;AAC9C,WAAO,GAAG,IAAI;AAAA,EAChB;AACA,MAAI,CAAC,MAAM;AACT,WAAO;AAAA,EACT;AACA,MAAI,MAAM,QAAQ,IAAI,GAAG;AACvB,WAAO,KAAK,IAAI,WAAW,EAAE,KAAK,EAAE;AAAA,EACtC;AACA,MAAI,OAAO,SAAS,YAAY,WAAW,MAAM;AAC/C,WAAO,YAAY,KAAK,MAAM,QAAQ;AAAA,EACxC;AACA,QAAM,IAAI,MAAM,sBAAsB,OAAO,I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AS,SAAS,KAAK,CAAC;AAAA,IACrD;AAAA,EACF;AACF;AAEO,SAAS,4BAA4B,OAAyB;AACnE,SAAO,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,YAAY,SAAS,MAAM,WAAW;AACvF;AAEO,IAAM,0BAAN,cAAsC,MAAM;AAAA,EAIjD,YAAY,SAA8B;AACxC,UAAM;AAAA;AAAA;AAAA,QAGF,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kHAWwE,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA,6GAGvC,QAAQ,UAAU,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAW1I;AAED,SAAK,OAAO;AACZ,SAAK,SAAS,QAAQ,UAAU;AAIhC,SAAK,SAAS;AAAA,EAChB;AACF;AA0BO,SAAS,aAAa,QAAiB;AAC5C,MAAI,KAAC,0BAAc,GAAG;AACpB,UAAM,IAAI,wBAAwB,EAAE,OAAO,CAAC;AAAA,EAC9C;AACF;","names":["React"]}
@@ -0,0 +1,3 @@
1
+ declare function createCachedRegex(pattern: string): RegExp;
2
+
3
+ export { createCachedRegex };
@@ -0,0 +1,3 @@
1
+ declare function createCachedRegex(pattern: string): RegExp;
2
+
3
+ export { createCachedRegex };
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/utils/regex.tsx
21
+ var regex_exports = {};
22
+ __export(regex_exports, {
23
+ createCachedRegex: () => createCachedRegex
24
+ });
25
+ module.exports = __toCommonJS(regex_exports);
26
+ var cachedRegexes = /* @__PURE__ */ new Map();
27
+ function createCachedRegex(pattern) {
28
+ const cached = cachedRegexes.get(pattern);
29
+ if (cached) return cached;
30
+ const regex = new RegExp(pattern);
31
+ cachedRegexes.set(pattern, regex);
32
+ return regex;
33
+ }
34
+ // Annotate the CommonJS export names for ESM import in node:
35
+ 0 && (module.exports = {
36
+ createCachedRegex
37
+ });
38
+ //# sourceMappingURL=regex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/regex.tsx"],"sourcesContent":["const cachedRegexes = new Map<string, RegExp>();\n\nexport function createCachedRegex(pattern: string) {\n const cached = cachedRegexes.get(pattern);\n if (cached) return cached;\n\n const regex = new RegExp(pattern);\n cachedRegexes.set(pattern, regex);\n return regex;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAM,gBAAgB,oBAAI,IAAoB;AAEvC,SAAS,kBAAkB,SAAiB;AACjD,QAAM,SAAS,cAAc,IAAI,OAAO;AACxC,MAAI,OAAQ,QAAO;AAEnB,QAAM,QAAQ,IAAI,OAAO,OAAO;AAChC,gBAAc,IAAI,SAAS,KAAK;AAChC,SAAO;AACT;","names":[]}
@@ -117,7 +117,7 @@ function mergeScopeStrings(...scopes) {
117
117
  return extractScopes(allScope).join(" ");
118
118
  }
119
119
  function escapeTemplateLiteral(s) {
120
- return s.replaceAll("`", "\\`").replaceAll("\\", "\\\\").replaceAll("$", "\\$");
120
+ return s.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${");
121
121
  }
122
122
  var nicifiableClassNameOverrides = new Map(Object.entries({
123
123
  Headers
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/strings.tsx"],"sourcesContent":["import { findLastIndex, unique } from \"./arrays\";\nimport { StackAssertionError } from \"./errors\";\nimport { filterUndefined } from \"./objects\";\n\nexport type Join<T extends string[], Separator extends string> =\n T extends [] ? \"\"\n : T extends [infer U extends string, ...infer Rest extends string[]]\n ? `${U}${Rest extends [any, ...any[]] ? `${Separator}${Join<Rest, Separator>}` : \"\"}`\n : \"<error-joining-strings>\";\n\nexport function typedJoin<T extends string[], Separator extends string>(strings: T, separator: Separator): Join<T, Separator> {\n return strings.join(separator) as Join<T, Separator>;\n}\n\nexport function typedToLowercase<S extends string>(s: S): Lowercase<S> {\n if (typeof s !== \"string\") throw new StackAssertionError(\"Expected a string for typedToLowercase\", { s });\n return s.toLowerCase() as Lowercase<S>;\n}\nundefined?.test(\"typedToLowercase\", ({ expect }) => {\n expect(typedToLowercase(\"\")).toBe(\"\");\n expect(typedToLowercase(\"HELLO\")).toBe(\"hello\");\n expect(typedToLowercase(\"Hello World\")).toBe(\"hello world\");\n expect(typedToLowercase(\"hello\")).toBe(\"hello\");\n expect(typedToLowercase(\"123\")).toBe(\"123\");\n expect(typedToLowercase(\"MIXED123case\")).toBe(\"mixed123case\");\n expect(typedToLowercase(\"Special@Chars!\")).toBe(\"special@chars!\");\n expect(() => typedToLowercase(123 as any)).toThrow(\"Expected a string for typedToLowercase\");\n});\n\nexport function typedToUppercase<S extends string>(s: S): Uppercase<S> {\n if (typeof s !== \"string\") throw new StackAssertionError(\"Expected a string for typedToUppercase\", { s });\n return s.toUpperCase() as Uppercase<S>;\n}\nundefined?.test(\"typedToUppercase\", ({ expect }) => {\n expect(typedToUppercase(\"\")).toBe(\"\");\n expect(typedToUppercase(\"hello\")).toBe(\"HELLO\");\n expect(typedToUppercase(\"Hello World\")).toBe(\"HELLO WORLD\");\n expect(typedToUppercase(\"HELLO\")).toBe(\"HELLO\");\n expect(typedToUppercase(\"123\")).toBe(\"123\");\n expect(typedToUppercase(\"mixed123Case\")).toBe(\"MIXED123CASE\");\n expect(typedToUppercase(\"special@chars!\")).toBe(\"SPECIAL@CHARS!\");\n expect(() => typedToUppercase(123 as any)).toThrow(\"Expected a string for typedToUppercase\");\n});\n\nexport function typedCapitalize<S extends string>(s: S): Capitalize<S> {\n return s.charAt(0).toUpperCase() + s.slice(1) as Capitalize<S>;\n}\nundefined?.test(\"typedCapitalize\", ({ expect }) => {\n expect(typedCapitalize(\"\")).toBe(\"\");\n expect(typedCapitalize(\"hello\")).toBe(\"Hello\");\n expect(typedCapitalize(\"hello world\")).toBe(\"Hello world\");\n expect(typedCapitalize(\"HELLO\")).toBe(\"HELLO\");\n expect(typedCapitalize(\"123test\")).toBe(\"123test\");\n expect(typedCapitalize(\"already Capitalized\")).toBe(\"Already Capitalized\");\n expect(typedCapitalize(\"h\")).toBe(\"H\");\n});\n\n/**\n * Compares two strings in a way that is not dependent on the current locale.\n */\nexport function stringCompare(a: string, b: string): number {\n if (typeof a !== \"string\" || typeof b !== \"string\") throw new StackAssertionError(`Expected two strings for stringCompare, found ${typeof a} and ${typeof b}`, { a, b });\n const cmp = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;\n return cmp(a.toUpperCase(), b.toUpperCase()) || cmp(b, a);\n}\nundefined?.test(\"stringCompare\", ({ expect }) => {\n // Equal strings\n expect(stringCompare(\"a\", \"a\")).toBe(0);\n expect(stringCompare(\"\", \"\")).toBe(0);\n\n // Case comparison - note that this function is NOT case-insensitive\n // It compares uppercase versions first, then original strings\n expect(stringCompare(\"a\", \"A\")).toBe(-1); // lowercase comes after uppercase\n expect(stringCompare(\"A\", \"a\")).toBe(1); // uppercase comes before lowercase\n expect(stringCompare(\"abc\", \"ABC\")).toBe(-1);\n expect(stringCompare(\"ABC\", \"abc\")).toBe(1);\n\n // Different strings\n expect(stringCompare(\"a\", \"b\")).toBe(-1);\n expect(stringCompare(\"b\", \"a\")).toBe(1);\n\n // Strings with different lengths\n expect(stringCompare(\"abc\", \"abcd\")).toBe(-1);\n expect(stringCompare(\"abcd\", \"abc\")).toBe(1);\n\n // Strings with numbers\n expect(stringCompare(\"a1\", \"a2\")).toBe(-1);\n expect(stringCompare(\"a10\", \"a2\")).toBe(-1);\n\n // Strings with special characters\n expect(stringCompare(\"a\", \"a!\")).toBe(-1);\n expect(stringCompare(\"a!\", \"a\")).toBe(1);\n});\n\n/**\n * Returns all whitespace character at the start of the string.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function getWhitespacePrefix(s: string): string {\n return s.substring(0, s.length - s.trimStart().length);\n}\nundefined?.test(\"getWhitespacePrefix\", ({ expect }) => {\n expect(getWhitespacePrefix(\"\")).toBe(\"\");\n expect(getWhitespacePrefix(\"hello\")).toBe(\"\");\n expect(getWhitespacePrefix(\" hello\")).toBe(\" \");\n expect(getWhitespacePrefix(\" hello\")).toBe(\" \");\n expect(getWhitespacePrefix(\"\\thello\")).toBe(\"\\t\");\n expect(getWhitespacePrefix(\"\\n hello\")).toBe(\"\\n \");\n expect(getWhitespacePrefix(\" \")).toBe(\" \");\n expect(getWhitespacePrefix(\" \\t\\n\\r\")).toBe(\" \\t\\n\\r\");\n});\n\n/**\n * Returns all whitespace character at the end of the string.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function getWhitespaceSuffix(s: string): string {\n return s.substring(s.trimEnd().length);\n}\nundefined?.test(\"getWhitespaceSuffix\", ({ expect }) => {\n expect(getWhitespaceSuffix(\"\")).toBe(\"\");\n expect(getWhitespaceSuffix(\"hello\")).toBe(\"\");\n expect(getWhitespaceSuffix(\"hello \")).toBe(\" \");\n expect(getWhitespaceSuffix(\"hello \")).toBe(\" \");\n expect(getWhitespaceSuffix(\"hello\\t\")).toBe(\"\\t\");\n expect(getWhitespaceSuffix(\"hello \\n\")).toBe(\" \\n\");\n expect(getWhitespaceSuffix(\" \")).toBe(\" \");\n expect(getWhitespaceSuffix(\" \\t\\n\\r\")).toBe(\" \\t\\n\\r\");\n});\n\n/**\n * Returns a string with all empty or whitespace-only lines at the start removed.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function trimEmptyLinesStart(s: string): string {\n const lines = s.split(\"\\n\");\n const firstNonEmptyLineIndex = lines.findIndex((line) => line.trim() !== \"\");\n // If all lines are empty or whitespace-only, return an empty string\n if (firstNonEmptyLineIndex === -1) return \"\";\n return lines.slice(firstNonEmptyLineIndex).join(\"\\n\");\n}\nundefined?.test(\"trimEmptyLinesStart\", ({ expect }) => {\n expect(trimEmptyLinesStart(\"\")).toBe(\"\");\n expect(trimEmptyLinesStart(\"hello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\"\\nhello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\"\\n\\nhello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\" \\n\\t\\nhello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\"\\n\\nhello\\nworld\")).toBe(\"hello\\nworld\");\n expect(trimEmptyLinesStart(\"hello\\n\\nworld\")).toBe(\"hello\\n\\nworld\");\n expect(trimEmptyLinesStart(\"hello\\nworld\\n\")).toBe(\"hello\\nworld\\n\");\n expect(trimEmptyLinesStart(\"\\n \\n\\nhello\\n \\nworld\")).toBe(\"hello\\n \\nworld\");\n // Edge case: all lines are empty\n expect(trimEmptyLinesStart(\"\\n\\n \\n\\t\")).toBe(\"\");\n});\n\n/**\n * Returns a string with all empty or whitespace-only lines at the end removed.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function trimEmptyLinesEnd(s: string): string {\n const lines = s.split(\"\\n\");\n const lastNonEmptyLineIndex = findLastIndex(lines, (line) => line.trim() !== \"\");\n return lines.slice(0, lastNonEmptyLineIndex + 1).join(\"\\n\");\n}\nundefined?.test(\"trimEmptyLinesEnd\", ({ expect }) => {\n expect(trimEmptyLinesEnd(\"\")).toBe(\"\");\n expect(trimEmptyLinesEnd(\"hello\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\n\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\n\\n\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\n \\n\\t\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\nworld\\n\\n\")).toBe(\"hello\\nworld\");\n expect(trimEmptyLinesEnd(\"hello\\n\\nworld\")).toBe(\"hello\\n\\nworld\");\n expect(trimEmptyLinesEnd(\"\\nhello\\nworld\")).toBe(\"\\nhello\\nworld\");\n expect(trimEmptyLinesEnd(\"hello\\n \\nworld\\n\\n \")).toBe(\"hello\\n \\nworld\");\n // Edge case: all lines are empty\n expect(trimEmptyLinesEnd(\"\\n\\n \\n\\t\")).toBe(\"\");\n});\n\n/**\n * Returns a string with all empty or whitespace-only lines trimmed at the start and end.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function trimLines(s: string): string {\n return trimEmptyLinesEnd(trimEmptyLinesStart(s));\n}\nundefined?.test(\"trimLines\", ({ expect }) => {\n expect(trimLines(\"\")).toBe(\"\");\n expect(trimLines(\" \")).toBe(\"\");\n expect(trimLines(\" \\n \")).toBe(\"\");\n expect(trimLines(\" abc \")).toBe(\" abc \");\n expect(trimLines(\"\\n \\nLine1\\nLine2\\n \\n\")).toBe(\"Line1\\nLine2\");\n expect(trimLines(\"Line1\\n \\nLine2\")).toBe(\"Line1\\n \\nLine2\");\n expect(trimLines(\" \\n \\n\\t\")).toBe(\"\");\n expect(trimLines(\" Hello World\")).toBe(\" Hello World\");\n expect(trimLines(\"\\n\")).toBe(\"\");\n expect(trimLines(\"\\t \\n\\t\\tLine1 \\n \\nLine2\\t\\t\\n\\t \")).toBe(\"\\t\\tLine1 \\n \\nLine2\\t\\t\");\n});\n\n\n/**\n * A template literal tag that returns the same string as the template literal without a tag.\n *\n * Useful for implementing your own template literal tags.\n */\nexport function templateIdentity(strings: TemplateStringsArray | readonly string[], ...values: string[]): string {\n if (values.length !== strings.length - 1) throw new StackAssertionError(\"Invalid number of values; must be one less than strings\", { strings, values });\n\n return strings.reduce((result, str, i) => result + str + (values[i] ?? ''), '');\n}\nundefined?.test(\"templateIdentity\", ({ expect }) => {\n expect(templateIdentity`Hello World`).toBe(\"Hello World\");\n expect(templateIdentity`${\"Hello\"}`).toBe(\"Hello\");\n const greeting = \"Hello\";\n const subject = \"World\";\n expect(templateIdentity`${greeting}, ${subject}!`).toBe(\"Hello, World!\");\n expect(templateIdentity`${\"A\"}${\"B\"}${\"C\"}`).toBe(\"ABC\");\n expect(templateIdentity`Start${\"\"}Middle${\"\"}End`).toBe(\"StartMiddleEnd\");\n expect(templateIdentity``).toBe(\"\");\n expect(templateIdentity`Line1\nLine2`).toBe(\"Line1\\nLine2\");\n expect(templateIdentity([\"a \", \" scientific \", \"gun\"], \"certain\", \"rail\")).toBe(\"a certain scientific railgun\");\n expect(templateIdentity([\"only one part\"])).toBe(\"only one part\");\n expect(() => templateIdentity([\"a \", \"b\", \"c\"], \"only one\")).toThrow(\"Invalid number of values\");\n expect(() => templateIdentity([\"a\", \"b\"], \"x\", \"y\")).toThrow(\"Invalid number of values\");\n});\n\n\nexport function deindent(code: string): string;\nexport function deindent(strings: TemplateStringsArray | readonly string[], ...values: any[]): string;\nexport function deindent(strings: string | readonly string[], ...values: any[]): string {\n if (typeof strings === \"string\") return deindent([strings]);\n return templateIdentity(...deindentTemplate(strings, ...values));\n}\n\nexport function deindentTemplate(strings: TemplateStringsArray | readonly string[], ...values: any[]): [string[], ...string[]] {\n if (values.length !== strings.length - 1) throw new StackAssertionError(\"Invalid number of values; must be one less than strings\", { strings, values });\n\n const trimmedStrings = [...strings];\n trimmedStrings[0] = trimEmptyLinesStart(trimmedStrings[0] + \"+\").slice(0, -1);\n trimmedStrings[trimmedStrings.length - 1] = trimEmptyLinesEnd(\"+\" + trimmedStrings[trimmedStrings.length - 1]).slice(1);\n\n const indentation = trimmedStrings\n .join(\"${SOME_VALUE}\")\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\")\n .map((line) => getWhitespacePrefix(line).length)\n .reduce((min, current) => Math.min(min, current), Infinity);\n\n const deindentedStrings = trimmedStrings\n .map((string, stringIndex) => {\n return string\n .split(\"\\n\")\n .map((line, lineIndex) => stringIndex !== 0 && lineIndex === 0 ? line : line.substring(indentation))\n .join(\"\\n\");\n });\n\n const indentedValues = values.map((value, i) => {\n const firstLineIndentation = getWhitespacePrefix(deindentedStrings[i].split(\"\\n\").at(-1)!);\n return `${value}`.replaceAll(\"\\n\", `\\n${firstLineIndentation}`);\n });\n\n return [deindentedStrings, ...indentedValues];\n}\nundefined?.test(\"deindent\", ({ expect }) => {\n // Test with string input\n expect(deindent(\" hello\")).toBe(\"hello\");\n expect(deindent(\" hello\\n world\")).toBe(\"hello\\nworld\");\n expect(deindent(\" hello\\n world\")).toBe(\"hello\\n world\");\n expect(deindent(\"\\n hello\\n world\\n\")).toBe(\"hello\\nworld\");\n\n // Test with empty input\n expect(deindent(\"\")).toBe(\"\");\n\n // Test with template literal\n expect(deindent`\n hello\n world\n `).toBe(\"hello\\nworld\");\n\n expect(deindent`\n hello\n world\n `).toBe(\"hello\\n world\");\n\n // Test with values\n const value = \"test\";\n expect(deindent`\n hello ${value}\n world\n `).toBe(`hello ${value}\\nworld`);\n\n // Test with multiline values\n expect(deindent`\n hello\n to ${\"line1\\n line2\"}\n world\n `).toBe(`hello\\n to line1\\n line2\\nworld`);\n\n // Leading whitespace values\n expect(deindent`\n ${\" \"}A\n ${\" \"}B\n ${\" \"}C\n `).toBe(` A\\n B\\n C`);\n\n // Trailing whitespaces (note: there are two whitespaces each after A and after C)\n expect(deindent`\n A \n B ${\" \"}\n C \n `).toBe(`A \\nB \\nC `);\n\n // Test with mixed indentation\n expect(deindent`\n hello\n world\n !\n `).toBe(\"hello\\n world\\n !\");\n\n // Test error cases\n expect(() => deindent([\"a\", \"b\", \"c\"], \"too\", \"many\", \"values\")).toThrow(\"Invalid number of values\");\n});\n\nexport function extractScopes(scope: string, removeDuplicates=true): string[] {\n // TODO what is this for? can we move this into the OAuth code in the backend?\n const trimmedString = scope.trim();\n const scopesArray = trimmedString.split(/\\s+/);\n const filtered = scopesArray.filter(scope => scope.length > 0);\n return removeDuplicates ? [...new Set(filtered)] : filtered;\n}\nundefined?.test(\"extractScopes\", ({ expect }) => {\n // Test with empty string\n expect(extractScopes(\"\")).toEqual([]);\n\n // Test with single scope\n expect(extractScopes(\"read\")).toEqual([\"read\"]);\n\n // Test with multiple scopes\n expect(extractScopes(\"read write\")).toEqual([\"read\", \"write\"]);\n\n // Test with extra whitespace\n expect(extractScopes(\" read write \")).toEqual([\"read\", \"write\"]);\n\n // Test with newlines and tabs\n expect(extractScopes(\"read\\nwrite\\tdelete\")).toEqual([\"read\", \"write\", \"delete\"]);\n\n // Test with duplicates (default behavior)\n expect(extractScopes(\"read write read\")).toEqual([\"read\", \"write\"]);\n\n // Test with duplicates (explicitly set to remove)\n expect(extractScopes(\"read write read\", true)).toEqual([\"read\", \"write\"]);\n\n // Test with duplicates (explicitly set to keep)\n expect(extractScopes(\"read write read\", false)).toEqual([\"read\", \"write\", \"read\"]);\n});\n\nexport function mergeScopeStrings(...scopes: string[]): string {\n // TODO what is this for? can we move this into the OAuth code in the backend?\n const allScope = scopes.map((s) => extractScopes(s)).flat().join(\" \");\n return extractScopes(allScope).join(\" \");\n}\nundefined?.test(\"mergeScopeStrings\", ({ expect }) => {\n // Test with empty input\n expect(mergeScopeStrings()).toBe(\"\");\n\n // Test with single scope string\n expect(mergeScopeStrings(\"read write\")).toBe(\"read write\");\n\n // Test with multiple scope strings\n expect(mergeScopeStrings(\"read\", \"write\")).toBe(\"read write\");\n\n // Test with overlapping scopes\n expect(mergeScopeStrings(\"read write\", \"write delete\")).toBe(\"read write delete\");\n\n // Test with extra whitespace\n expect(mergeScopeStrings(\" read write \", \" delete \")).toBe(\"read write delete\");\n\n // Test with duplicates across strings\n expect(mergeScopeStrings(\"read write\", \"write delete\", \"read\")).toBe(\"read write delete\");\n\n // Test with empty strings\n expect(mergeScopeStrings(\"read write\", \"\", \"delete\")).toBe(\"read write delete\");\n});\n\nexport function escapeTemplateLiteral(s: string): string {\n return s.replaceAll(\"`\", \"\\\\`\").replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"$\", \"\\\\$\");\n}\nundefined?.test(\"escapeTemplateLiteral\", ({ expect }) => {\n // Test with empty string\n expect(escapeTemplateLiteral(\"\")).toBe(\"\");\n\n // Test with normal string (no special characters)\n expect(escapeTemplateLiteral(\"hello world\")).toBe(\"hello world\");\n\n // Test with backtick\n const input1 = \"hello `world`\";\n const output1 = escapeTemplateLiteral(input1);\n // Verify backticks are escaped\n expect(output1.includes(\"\\\\`\")).toBe(true);\n expect(output1).not.toBe(input1);\n\n // Test with backslash\n const input2 = \"hello \\\\world\";\n const output2 = escapeTemplateLiteral(input2);\n // Verify backslashes are escaped\n expect(output2.includes(\"\\\\\\\\\")).toBe(true);\n expect(output2).not.toBe(input2);\n\n // Test with dollar sign\n const input3 = \"hello $world\";\n const output3 = escapeTemplateLiteral(input3);\n // Verify dollar signs are escaped\n expect(output3.includes(\"\\\\$\")).toBe(true);\n expect(output3).not.toBe(input3);\n\n // Test with multiple special characters\n const input4 = \"`hello` $world\\\\\";\n const output4 = escapeTemplateLiteral(input4);\n // Verify all special characters are escaped\n expect(output4.includes(\"\\\\`\")).toBe(true);\n expect(output4.includes(\"\\\\$\")).toBe(true);\n expect(output4.includes(\"\\\\\\\\\")).toBe(true);\n expect(output4).not.toBe(input4);\n\n // Test with already escaped characters\n const input5 = \"\\\\`hello\\\\`\";\n const output5 = escapeTemplateLiteral(input5);\n // Verify already escaped characters are properly escaped\n expect(output5).not.toBe(input5);\n});\n\n/**\n * Some classes have different constructor names in different environments (eg. `Headers` is sometimes called `_Headers`,\n * so we create an object of overrides to handle these cases.\n */\nconst nicifiableClassNameOverrides = new Map(Object.entries({\n Headers,\n} as Record<string, unknown>).map(([k, v]) => [v, k]));\nexport type Nicifiable = {\n getNicifiableKeys?(): PropertyKey[],\n getNicifiedObjectExtraLines?(): string[],\n};\nexport type NicifyOptions = {\n maxDepth: number,\n currentIndent: string,\n lineIndent: string,\n multiline: boolean,\n refs: Map<unknown, string>,\n path: string,\n parent: null | {\n options: NicifyOptions,\n value: unknown,\n },\n keyInParent: PropertyKey | null,\n hideFields: PropertyKey[],\n overrides: (...args: Parameters<typeof nicify>) => string | null,\n};\nexport function nicify(\n value: unknown,\n options: Partial<NicifyOptions> = {},\n): string {\n const fullOptions: NicifyOptions = {\n maxDepth: 5,\n currentIndent: \"\",\n lineIndent: \" \",\n multiline: true,\n refs: new Map(),\n path: \"value\",\n parent: null,\n overrides: () => null,\n keyInParent: null,\n hideFields: [],\n ...filterUndefined(options),\n };\n const {\n maxDepth,\n currentIndent,\n lineIndent,\n multiline,\n refs,\n path,\n overrides,\n hideFields,\n } = fullOptions;\n const nl = `\\n${currentIndent}`;\n\n const overrideResult = overrides(value, options);\n if (overrideResult !== null) return overrideResult;\n\n if ([\"function\", \"object\", \"symbol\"].includes(typeof value) && value !== null) {\n if (refs.has(value)) {\n return `Ref<${refs.get(value)}>`;\n }\n refs.set(value, path);\n }\n\n const newOptions: NicifyOptions = {\n maxDepth: maxDepth - 1,\n currentIndent,\n lineIndent,\n multiline,\n refs,\n path: path + \"->[unknown property]\",\n overrides,\n parent: { value, options: fullOptions },\n keyInParent: null,\n hideFields: [],\n };\n const nestedNicify = (newValue: unknown, newPath: string, keyInParent: PropertyKey | null, options: Partial<NicifyOptions> = {}) => {\n return nicify(newValue, {\n ...newOptions,\n path: newPath,\n currentIndent: currentIndent + lineIndent,\n keyInParent,\n ...options,\n });\n };\n\n switch (typeof value) {\n case \"boolean\": case \"number\": {\n return JSON.stringify(value);\n }\n case \"string\": {\n const isDeindentable = (v: string) => deindent(v) === v && v.includes(\"\\n\");\n const wrapInDeindent = (v: string) => deindent`\n deindent\\`\n ${currentIndent + lineIndent}${escapeTemplateLiteral(v).replaceAll(\"\\n\", nl + lineIndent)}\n ${currentIndent}\\`\n `;\n if (isDeindentable(value)) {\n return wrapInDeindent(value);\n } else if (value.endsWith(\"\\n\") && isDeindentable(value.slice(0, -1))) {\n return wrapInDeindent(value.slice(0, -1)) + ' + \"\\\\n\"';\n } else {\n return JSON.stringify(value);\n }\n }\n case \"undefined\": {\n return \"undefined\";\n }\n case \"symbol\": {\n return value.toString();\n }\n case \"bigint\": {\n return `${value}n`;\n }\n case \"function\": {\n if (value.name) return `function ${value.name}(...) { ... }`;\n return `(...) => { ... }`;\n }\n case \"object\": {\n if (value === null) return \"null\";\n if (Array.isArray(value)) {\n const extraLines = getNicifiedObjectExtraLines(value);\n const resValueLength = value.length + extraLines.length;\n if (resValueLength === 0) return \"[]\"; // early return in case maxDepth <= 0\n if (maxDepth <= 0) return `[...]`;\n const resValues = value.map((v, i) => nestedNicify(v, `${path}[${i}]`, i));\n resValues.push(...extraLines);\n if (resValues.length !== resValueLength) throw new StackAssertionError(\"nicify of object: resValues.length !== resValueLength\", { value, resValues, resValueLength });\n const shouldIndent = resValues.length > 4 || resValues.some(x => (resValues.length > 1 && x.length > 4) || x.includes(\"\\n\"));\n if (shouldIndent) {\n return `[${nl}${resValues.map(x => `${lineIndent}${x},${nl}`).join(\"\")}]`;\n } else {\n return `[${resValues.join(\", \")}]`;\n }\n }\n if (value instanceof Date) {\n return `Date(${nestedNicify(value.toISOString(), `${path}.toISOString()`, null)})`;\n }\n if (value instanceof URL) {\n return `URL(${nestedNicify(value.toString(), `${path}.toString()`, null)})`;\n }\n if (ArrayBuffer.isView(value)) {\n return `${value.constructor.name}([${value.toString()}])`;\n }\n if (value instanceof ArrayBuffer) {\n return `ArrayBuffer [${new Uint8Array(value).toString()}]`;\n }\n if (value instanceof Error) {\n let stack = value.stack ?? \"\";\n const toString = value.toString();\n if (!stack.startsWith(toString)) stack = `${toString}\\n${stack}`; // some browsers don't include the error message in the stack, some do\n stack = stack.trimEnd();\n stack = stack.replace(/\\n\\s+/g, `\\n${lineIndent}${lineIndent}`);\n stack = stack.replace(\"\\n\", `\\n${lineIndent}Stack:\\n`);\n if (Object.keys(value).length > 0) {\n stack += `\\n${lineIndent}Extra properties: ${nestedNicify(Object.fromEntries(Object.entries(value)), path, null)}`;\n }\n if (value.cause) {\n stack += `\\n${lineIndent}Cause:\\n${lineIndent}${lineIndent}${nestedNicify(value.cause, path, null, { currentIndent: currentIndent + lineIndent + lineIndent })}`;\n }\n stack = stack.replaceAll(\"\\n\", `\\n${currentIndent}`);\n return stack;\n }\n\n const constructorName = [null, Object.prototype].includes(Object.getPrototypeOf(value)) ? null : (nicifiableClassNameOverrides.get(value.constructor) ?? value.constructor.name);\n const constructorString = constructorName ? `${constructorName} ` : \"\";\n\n const entries = getNicifiableEntries(value).filter(([k]) => !hideFields.includes(k));\n const extraLines = [\n ...getNicifiedObjectExtraLines(value),\n ...hideFields.length > 0 ? [`<some fields may have been hidden>`] : [],\n ];\n const resValueLength = entries.length + extraLines.length;\n if (resValueLength === 0) return `${constructorString}{}`;\n if (maxDepth <= 0) return `${constructorString}{ ... }`;\n const resValues = entries.map(([k, v], keyIndex) => {\n const keyNicified = nestedNicify(k, `Object.keys(${path})[${keyIndex}]`, null);\n const keyInObjectLiteral = typeof k === \"string\" ? nicifyPropertyString(k) : `[${keyNicified}]`;\n if (typeof v === \"function\" && v.name === k) {\n return `${keyInObjectLiteral}(...): { ... }`;\n } else {\n return `${keyInObjectLiteral}: ${nestedNicify(v, `${path}[${keyNicified}]`, k)}`;\n }\n });\n resValues.push(...extraLines);\n if (resValues.length !== resValueLength) throw new StackAssertionError(\"nicify of object: resValues.length !== resValueLength\", { value, resValues, resValueLength });\n const shouldIndent = resValues.length > 1 || resValues.some(x => x.includes(\"\\n\"));\n\n if (resValues.length === 0) return `${constructorString}{}`;\n if (shouldIndent) {\n return `${constructorString}{${nl}${resValues.map(x => `${lineIndent}${x},${nl}`).join(\"\")}}`;\n } else {\n return `${constructorString}{ ${resValues.join(\", \")} }`;\n }\n }\n default: {\n return `${typeof value}<${value}>`;\n }\n }\n}\n\nexport function replaceAll(input: string, searchValue: string, replaceValue: string): string {\n if (searchValue === \"\") throw new StackAssertionError(\"replaceAll: searchValue is empty\");\n return input.split(searchValue).join(replaceValue);\n}\nundefined?.test(\"replaceAll\", ({ expect }) => {\n expect(replaceAll(\"hello world\", \"o\", \"x\")).toBe(\"hellx wxrld\");\n expect(replaceAll(\"aaa\", \"a\", \"b\")).toBe(\"bbb\");\n expect(replaceAll(\"\", \"a\", \"b\")).toBe(\"\");\n expect(replaceAll(\"abc\", \"b\", \"\")).toBe(\"ac\");\n expect(replaceAll(\"test.test.test\", \".\", \"_\")).toBe(\"test_test_test\");\n expect(replaceAll(\"a.b*c\", \".\", \"x\")).toBe(\"axb*c\");\n expect(replaceAll(\"a*b*c\", \"*\", \"x\")).toBe(\"axbxc\");\n expect(replaceAll(\"hello hello\", \"hello\", \"hi\")).toBe(\"hi hi\");\n});\n\nfunction nicifyPropertyString(str: string) {\n return JSON.stringify(str);\n}\nundefined?.test(\"nicifyPropertyString\", ({ expect }) => {\n // Test valid identifiers\n expect(nicifyPropertyString(\"validName\")).toBe('\"validName\"');\n expect(nicifyPropertyString(\"_validName\")).toBe('\"_validName\"');\n expect(nicifyPropertyString(\"valid123Name\")).toBe('\"valid123Name\"');\n\n // Test invalid identifiers\n expect(nicifyPropertyString(\"123invalid\")).toBe('\"123invalid\"');\n expect(nicifyPropertyString(\"invalid-name\")).toBe('\"invalid-name\"');\n expect(nicifyPropertyString(\"invalid space\")).toBe('\"invalid space\"');\n expect(nicifyPropertyString(\"$invalid\")).toBe('\"$invalid\"');\n expect(nicifyPropertyString(\"\")).toBe('\"\"');\n\n // Test with special characters\n expect(nicifyPropertyString(\"property!\")).toBe('\"property!\"');\n expect(nicifyPropertyString(\"property.name\")).toBe('\"property.name\"');\n\n // Test with escaped characters\n expect(nicifyPropertyString(\"\\\\\")).toBe('\"\\\\\\\\\"');\n expect(nicifyPropertyString('\"')).toBe('\"\\\\\"\"');\n});\n\nfunction getNicifiableKeys(value: Nicifiable | object) {\n const overridden = (\"getNicifiableKeys\" in value ? value.getNicifiableKeys?.bind(value) : null)?.();\n if (overridden != null) return overridden;\n if (value instanceof Response) {\n return ['status', 'headers'];\n }\n const keys = Object.keys(value).sort();\n return unique(keys);\n}\nundefined?.test(\"getNicifiableKeys\", ({ expect }) => {\n // Test regular object\n expect(getNicifiableKeys({ b: 1, a: 2, c: 3 })).toEqual([\"a\", \"b\", \"c\"]);\n\n // Test empty object\n expect(getNicifiableKeys({})).toEqual([]);\n\n\n expect(getNicifiableKeys(new Response())).toEqual([\"status\", \"headers\"]);\n\n // Test object with custom getNicifiableKeys\n const customObject = {\n a: 1,\n b: 2,\n getNicifiableKeys() {\n return [\"customKey1\", \"customKey2\"];\n }\n };\n expect(getNicifiableKeys(customObject)).toEqual([\"customKey1\", \"customKey2\"]);\n});\n\nfunction getNicifiableEntries(value: Nicifiable | object): [PropertyKey, unknown][] {\n const recordLikes = [Headers];\n function isRecordLike(value: unknown): value is InstanceType<typeof recordLikes[number]> {\n return recordLikes.some(x => value instanceof x);\n }\n\n if (isRecordLike(value)) {\n return [...value.entries()].sort(([a], [b]) => stringCompare(`${a}`, `${b}`));\n }\n const keys = getNicifiableKeys(value);\n return keys.map((k) => [k, value[k as never]] as [PropertyKey, unknown]);\n}\n\nfunction getNicifiedObjectExtraLines(value: Nicifiable | object) {\n return (\"getNicifiedObjectExtraLines\" in value ? value.getNicifiedObjectExtraLines : null)?.() ?? [];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAsC;AACtC,oBAAoC;AACpC,qBAAgC;AAQzB,SAAS,UAAwD,SAAY,WA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G,MAAM,QAAQ,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,cAAc,GAAG,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;AAAA,EAC9E;AACA,QAAM,OAAO,kBAAkB,KAAK;AACpC,SAAO,KAAK,IAAI,CAAC,MAAM,CAAC,GAAG,MAAM,CAAU,CAAC,CAA2B;AACzE;AAEA,SAAS,4BAA4B,OAA4B;AAC/D,UAAQ,iCAAiC,QAAQ,MAAM,8BAA8B,QAAQ,KAAK,CAAC;AACrG;","names":["a","b","scope","options","extraLines","resValueLength","resValues","shouldIndent","value"]}
1
+ {"version":3,"sources":["../../src/utils/strings.tsx"],"sourcesContent":["import { findLastIndex, unique } from \"./arrays\";\nimport { StackAssertionError } from \"./errors\";\nimport { filterUndefined } from \"./objects\";\n\nexport type Join<T extends string[], Separator extends string> =\n T extends [] ? \"\"\n : T extends [infer U extends string, ...infer Rest extends string[]]\n ? `${U}${Rest extends [any, ...any[]] ? `${Separator}${Join<Rest, Separator>}` : \"\"}`\n : \"<error-joining-strings>\";\n\nexport function typedJoin<T extends string[], Separator extends string>(strings: T, separator: Separator): Join<T, Separator> {\n return strings.join(separator) as Join<T, Separator>;\n}\n\nexport function typedToLowercase<S extends string>(s: S): Lowercase<S> {\n if (typeof s !== \"string\") throw new StackAssertionError(\"Expected a string for typedToLowercase\", { s });\n return s.toLowerCase() as Lowercase<S>;\n}\nundefined?.test(\"typedToLowercase\", ({ expect }) => {\n expect(typedToLowercase(\"\")).toBe(\"\");\n expect(typedToLowercase(\"HELLO\")).toBe(\"hello\");\n expect(typedToLowercase(\"Hello World\")).toBe(\"hello world\");\n expect(typedToLowercase(\"hello\")).toBe(\"hello\");\n expect(typedToLowercase(\"123\")).toBe(\"123\");\n expect(typedToLowercase(\"MIXED123case\")).toBe(\"mixed123case\");\n expect(typedToLowercase(\"Special@Chars!\")).toBe(\"special@chars!\");\n expect(() => typedToLowercase(123 as any)).toThrow(\"Expected a string for typedToLowercase\");\n});\n\nexport function typedToUppercase<S extends string>(s: S): Uppercase<S> {\n if (typeof s !== \"string\") throw new StackAssertionError(\"Expected a string for typedToUppercase\", { s });\n return s.toUpperCase() as Uppercase<S>;\n}\nundefined?.test(\"typedToUppercase\", ({ expect }) => {\n expect(typedToUppercase(\"\")).toBe(\"\");\n expect(typedToUppercase(\"hello\")).toBe(\"HELLO\");\n expect(typedToUppercase(\"Hello World\")).toBe(\"HELLO WORLD\");\n expect(typedToUppercase(\"HELLO\")).toBe(\"HELLO\");\n expect(typedToUppercase(\"123\")).toBe(\"123\");\n expect(typedToUppercase(\"mixed123Case\")).toBe(\"MIXED123CASE\");\n expect(typedToUppercase(\"special@chars!\")).toBe(\"SPECIAL@CHARS!\");\n expect(() => typedToUppercase(123 as any)).toThrow(\"Expected a string for typedToUppercase\");\n});\n\nexport function typedCapitalize<S extends string>(s: S): Capitalize<S> {\n return s.charAt(0).toUpperCase() + s.slice(1) as Capitalize<S>;\n}\nundefined?.test(\"typedCapitalize\", ({ expect }) => {\n expect(typedCapitalize(\"\")).toBe(\"\");\n expect(typedCapitalize(\"hello\")).toBe(\"Hello\");\n expect(typedCapitalize(\"hello world\")).toBe(\"Hello world\");\n expect(typedCapitalize(\"HELLO\")).toBe(\"HELLO\");\n expect(typedCapitalize(\"123test\")).toBe(\"123test\");\n expect(typedCapitalize(\"already Capitalized\")).toBe(\"Already Capitalized\");\n expect(typedCapitalize(\"h\")).toBe(\"H\");\n});\n\n/**\n * Compares two strings in a way that is not dependent on the current locale.\n */\nexport function stringCompare(a: string, b: string): number {\n if (typeof a !== \"string\" || typeof b !== \"string\") throw new StackAssertionError(`Expected two strings for stringCompare, found ${typeof a} and ${typeof b}`, { a, b });\n const cmp = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;\n return cmp(a.toUpperCase(), b.toUpperCase()) || cmp(b, a);\n}\nundefined?.test(\"stringCompare\", ({ expect }) => {\n // Equal strings\n expect(stringCompare(\"a\", \"a\")).toBe(0);\n expect(stringCompare(\"\", \"\")).toBe(0);\n\n // Case comparison - note that this function is NOT case-insensitive\n // It compares uppercase versions first, then original strings\n expect(stringCompare(\"a\", \"A\")).toBe(-1); // lowercase comes after uppercase\n expect(stringCompare(\"A\", \"a\")).toBe(1); // uppercase comes before lowercase\n expect(stringCompare(\"abc\", \"ABC\")).toBe(-1);\n expect(stringCompare(\"ABC\", \"abc\")).toBe(1);\n\n // Different strings\n expect(stringCompare(\"a\", \"b\")).toBe(-1);\n expect(stringCompare(\"b\", \"a\")).toBe(1);\n\n // Strings with different lengths\n expect(stringCompare(\"abc\", \"abcd\")).toBe(-1);\n expect(stringCompare(\"abcd\", \"abc\")).toBe(1);\n\n // Strings with numbers\n expect(stringCompare(\"a1\", \"a2\")).toBe(-1);\n expect(stringCompare(\"a10\", \"a2\")).toBe(-1);\n\n // Strings with special characters\n expect(stringCompare(\"a\", \"a!\")).toBe(-1);\n expect(stringCompare(\"a!\", \"a\")).toBe(1);\n});\n\n/**\n * Returns all whitespace character at the start of the string.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function getWhitespacePrefix(s: string): string {\n return s.substring(0, s.length - s.trimStart().length);\n}\nundefined?.test(\"getWhitespacePrefix\", ({ expect }) => {\n expect(getWhitespacePrefix(\"\")).toBe(\"\");\n expect(getWhitespacePrefix(\"hello\")).toBe(\"\");\n expect(getWhitespacePrefix(\" hello\")).toBe(\" \");\n expect(getWhitespacePrefix(\" hello\")).toBe(\" \");\n expect(getWhitespacePrefix(\"\\thello\")).toBe(\"\\t\");\n expect(getWhitespacePrefix(\"\\n hello\")).toBe(\"\\n \");\n expect(getWhitespacePrefix(\" \")).toBe(\" \");\n expect(getWhitespacePrefix(\" \\t\\n\\r\")).toBe(\" \\t\\n\\r\");\n});\n\n/**\n * Returns all whitespace character at the end of the string.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function getWhitespaceSuffix(s: string): string {\n return s.substring(s.trimEnd().length);\n}\nundefined?.test(\"getWhitespaceSuffix\", ({ expect }) => {\n expect(getWhitespaceSuffix(\"\")).toBe(\"\");\n expect(getWhitespaceSuffix(\"hello\")).toBe(\"\");\n expect(getWhitespaceSuffix(\"hello \")).toBe(\" \");\n expect(getWhitespaceSuffix(\"hello \")).toBe(\" \");\n expect(getWhitespaceSuffix(\"hello\\t\")).toBe(\"\\t\");\n expect(getWhitespaceSuffix(\"hello \\n\")).toBe(\" \\n\");\n expect(getWhitespaceSuffix(\" \")).toBe(\" \");\n expect(getWhitespaceSuffix(\" \\t\\n\\r\")).toBe(\" \\t\\n\\r\");\n});\n\n/**\n * Returns a string with all empty or whitespace-only lines at the start removed.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function trimEmptyLinesStart(s: string): string {\n const lines = s.split(\"\\n\");\n const firstNonEmptyLineIndex = lines.findIndex((line) => line.trim() !== \"\");\n // If all lines are empty or whitespace-only, return an empty string\n if (firstNonEmptyLineIndex === -1) return \"\";\n return lines.slice(firstNonEmptyLineIndex).join(\"\\n\");\n}\nundefined?.test(\"trimEmptyLinesStart\", ({ expect }) => {\n expect(trimEmptyLinesStart(\"\")).toBe(\"\");\n expect(trimEmptyLinesStart(\"hello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\"\\nhello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\"\\n\\nhello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\" \\n\\t\\nhello\")).toBe(\"hello\");\n expect(trimEmptyLinesStart(\"\\n\\nhello\\nworld\")).toBe(\"hello\\nworld\");\n expect(trimEmptyLinesStart(\"hello\\n\\nworld\")).toBe(\"hello\\n\\nworld\");\n expect(trimEmptyLinesStart(\"hello\\nworld\\n\")).toBe(\"hello\\nworld\\n\");\n expect(trimEmptyLinesStart(\"\\n \\n\\nhello\\n \\nworld\")).toBe(\"hello\\n \\nworld\");\n // Edge case: all lines are empty\n expect(trimEmptyLinesStart(\"\\n\\n \\n\\t\")).toBe(\"\");\n});\n\n/**\n * Returns a string with all empty or whitespace-only lines at the end removed.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function trimEmptyLinesEnd(s: string): string {\n const lines = s.split(\"\\n\");\n const lastNonEmptyLineIndex = findLastIndex(lines, (line) => line.trim() !== \"\");\n return lines.slice(0, lastNonEmptyLineIndex + 1).join(\"\\n\");\n}\nundefined?.test(\"trimEmptyLinesEnd\", ({ expect }) => {\n expect(trimEmptyLinesEnd(\"\")).toBe(\"\");\n expect(trimEmptyLinesEnd(\"hello\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\n\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\n\\n\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\n \\n\\t\")).toBe(\"hello\");\n expect(trimEmptyLinesEnd(\"hello\\nworld\\n\\n\")).toBe(\"hello\\nworld\");\n expect(trimEmptyLinesEnd(\"hello\\n\\nworld\")).toBe(\"hello\\n\\nworld\");\n expect(trimEmptyLinesEnd(\"\\nhello\\nworld\")).toBe(\"\\nhello\\nworld\");\n expect(trimEmptyLinesEnd(\"hello\\n \\nworld\\n\\n \")).toBe(\"hello\\n \\nworld\");\n // Edge case: all lines are empty\n expect(trimEmptyLinesEnd(\"\\n\\n \\n\\t\")).toBe(\"\");\n});\n\n/**\n * Returns a string with all empty or whitespace-only lines trimmed at the start and end.\n *\n * Uses the same definition for whitespace as `String.prototype.trim()`.\n */\nexport function trimLines(s: string): string {\n return trimEmptyLinesEnd(trimEmptyLinesStart(s));\n}\nundefined?.test(\"trimLines\", ({ expect }) => {\n expect(trimLines(\"\")).toBe(\"\");\n expect(trimLines(\" \")).toBe(\"\");\n expect(trimLines(\" \\n \")).toBe(\"\");\n expect(trimLines(\" abc \")).toBe(\" abc \");\n expect(trimLines(\"\\n \\nLine1\\nLine2\\n \\n\")).toBe(\"Line1\\nLine2\");\n expect(trimLines(\"Line1\\n \\nLine2\")).toBe(\"Line1\\n \\nLine2\");\n expect(trimLines(\" \\n \\n\\t\")).toBe(\"\");\n expect(trimLines(\" Hello World\")).toBe(\" Hello World\");\n expect(trimLines(\"\\n\")).toBe(\"\");\n expect(trimLines(\"\\t \\n\\t\\tLine1 \\n \\nLine2\\t\\t\\n\\t \")).toBe(\"\\t\\tLine1 \\n \\nLine2\\t\\t\");\n});\n\n\n/**\n * A template literal tag that returns the same string as the template literal without a tag.\n *\n * Useful for implementing your own template literal tags.\n */\nexport function templateIdentity(strings: TemplateStringsArray | readonly string[], ...values: string[]): string {\n if (values.length !== strings.length - 1) throw new StackAssertionError(\"Invalid number of values; must be one less than strings\", { strings, values });\n\n return strings.reduce((result, str, i) => result + str + (values[i] ?? ''), '');\n}\nundefined?.test(\"templateIdentity\", ({ expect }) => {\n expect(templateIdentity`Hello World`).toBe(\"Hello World\");\n expect(templateIdentity`${\"Hello\"}`).toBe(\"Hello\");\n const greeting = \"Hello\";\n const subject = \"World\";\n expect(templateIdentity`${greeting}, ${subject}!`).toBe(\"Hello, World!\");\n expect(templateIdentity`${\"A\"}${\"B\"}${\"C\"}`).toBe(\"ABC\");\n expect(templateIdentity`Start${\"\"}Middle${\"\"}End`).toBe(\"StartMiddleEnd\");\n expect(templateIdentity``).toBe(\"\");\n expect(templateIdentity`Line1\nLine2`).toBe(\"Line1\\nLine2\");\n expect(templateIdentity([\"a \", \" scientific \", \"gun\"], \"certain\", \"rail\")).toBe(\"a certain scientific railgun\");\n expect(templateIdentity([\"only one part\"])).toBe(\"only one part\");\n expect(() => templateIdentity([\"a \", \"b\", \"c\"], \"only one\")).toThrow(\"Invalid number of values\");\n expect(() => templateIdentity([\"a\", \"b\"], \"x\", \"y\")).toThrow(\"Invalid number of values\");\n});\n\n\nexport function deindent(code: string): string;\nexport function deindent(strings: TemplateStringsArray | readonly string[], ...values: any[]): string;\nexport function deindent(strings: string | readonly string[], ...values: any[]): string {\n if (typeof strings === \"string\") return deindent([strings]);\n return templateIdentity(...deindentTemplate(strings, ...values));\n}\n\nexport function deindentTemplate(strings: TemplateStringsArray | readonly string[], ...values: any[]): [string[], ...string[]] {\n if (values.length !== strings.length - 1) throw new StackAssertionError(\"Invalid number of values; must be one less than strings\", { strings, values });\n\n const trimmedStrings = [...strings];\n trimmedStrings[0] = trimEmptyLinesStart(trimmedStrings[0] + \"+\").slice(0, -1);\n trimmedStrings[trimmedStrings.length - 1] = trimEmptyLinesEnd(\"+\" + trimmedStrings[trimmedStrings.length - 1]).slice(1);\n\n const indentation = trimmedStrings\n .join(\"${SOME_VALUE}\")\n .split(\"\\n\")\n .filter((line) => line.trim() !== \"\")\n .map((line) => getWhitespacePrefix(line).length)\n .reduce((min, current) => Math.min(min, current), Infinity);\n\n const deindentedStrings = trimmedStrings\n .map((string, stringIndex) => {\n return string\n .split(\"\\n\")\n .map((line, lineIndex) => stringIndex !== 0 && lineIndex === 0 ? line : line.substring(indentation))\n .join(\"\\n\");\n });\n\n const indentedValues = values.map((value, i) => {\n const firstLineIndentation = getWhitespacePrefix(deindentedStrings[i].split(\"\\n\").at(-1)!);\n return `${value}`.replaceAll(\"\\n\", `\\n${firstLineIndentation}`);\n });\n\n return [deindentedStrings, ...indentedValues];\n}\nundefined?.test(\"deindent\", ({ expect }) => {\n // Test with string input\n expect(deindent(\" hello\")).toBe(\"hello\");\n expect(deindent(\" hello\\n world\")).toBe(\"hello\\nworld\");\n expect(deindent(\" hello\\n world\")).toBe(\"hello\\n world\");\n expect(deindent(\"\\n hello\\n world\\n\")).toBe(\"hello\\nworld\");\n\n // Test with empty input\n expect(deindent(\"\")).toBe(\"\");\n\n // Test with template literal\n expect(deindent`\n hello\n world\n `).toBe(\"hello\\nworld\");\n\n expect(deindent`\n hello\n world\n `).toBe(\"hello\\n world\");\n\n // Test with values\n const value = \"test\";\n expect(deindent`\n hello ${value}\n world\n `).toBe(`hello ${value}\\nworld`);\n\n // Test with multiline values\n expect(deindent`\n hello\n to ${\"line1\\n line2\"}\n world\n `).toBe(`hello\\n to line1\\n line2\\nworld`);\n\n // Leading whitespace values\n expect(deindent`\n ${\" \"}A\n ${\" \"}B\n ${\" \"}C\n `).toBe(` A\\n B\\n C`);\n\n // Trailing whitespaces (note: there are two whitespaces each after A and after C)\n expect(deindent`\n A \n B ${\" \"}\n C \n `).toBe(`A \\nB \\nC `);\n\n // Test with mixed indentation\n expect(deindent`\n hello\n world\n !\n `).toBe(\"hello\\n world\\n !\");\n\n // Test error cases\n expect(() => deindent([\"a\", \"b\", \"c\"], \"too\", \"many\", \"values\")).toThrow(\"Invalid number of values\");\n});\n\nexport function extractScopes(scope: string, removeDuplicates=true): string[] {\n // TODO what is this for? can we move this into the OAuth code in the backend?\n const trimmedString = scope.trim();\n const scopesArray = trimmedString.split(/\\s+/);\n const filtered = scopesArray.filter(scope => scope.length > 0);\n return removeDuplicates ? [...new Set(filtered)] : filtered;\n}\nundefined?.test(\"extractScopes\", ({ expect }) => {\n // Test with empty string\n expect(extractScopes(\"\")).toEqual([]);\n\n // Test with single scope\n expect(extractScopes(\"read\")).toEqual([\"read\"]);\n\n // Test with multiple scopes\n expect(extractScopes(\"read write\")).toEqual([\"read\", \"write\"]);\n\n // Test with extra whitespace\n expect(extractScopes(\" read write \")).toEqual([\"read\", \"write\"]);\n\n // Test with newlines and tabs\n expect(extractScopes(\"read\\nwrite\\tdelete\")).toEqual([\"read\", \"write\", \"delete\"]);\n\n // Test with duplicates (default behavior)\n expect(extractScopes(\"read write read\")).toEqual([\"read\", \"write\"]);\n\n // Test with duplicates (explicitly set to remove)\n expect(extractScopes(\"read write read\", true)).toEqual([\"read\", \"write\"]);\n\n // Test with duplicates (explicitly set to keep)\n expect(extractScopes(\"read write read\", false)).toEqual([\"read\", \"write\", \"read\"]);\n});\n\nexport function mergeScopeStrings(...scopes: string[]): string {\n // TODO what is this for? can we move this into the OAuth code in the backend?\n const allScope = scopes.map((s) => extractScopes(s)).flat().join(\" \");\n return extractScopes(allScope).join(\" \");\n}\nundefined?.test(\"mergeScopeStrings\", ({ expect }) => {\n // Test with empty input\n expect(mergeScopeStrings()).toBe(\"\");\n\n // Test with single scope string\n expect(mergeScopeStrings(\"read write\")).toBe(\"read write\");\n\n // Test with multiple scope strings\n expect(mergeScopeStrings(\"read\", \"write\")).toBe(\"read write\");\n\n // Test with overlapping scopes\n expect(mergeScopeStrings(\"read write\", \"write delete\")).toBe(\"read write delete\");\n\n // Test with extra whitespace\n expect(mergeScopeStrings(\" read write \", \" delete \")).toBe(\"read write delete\");\n\n // Test with duplicates across strings\n expect(mergeScopeStrings(\"read write\", \"write delete\", \"read\")).toBe(\"read write delete\");\n\n // Test with empty strings\n expect(mergeScopeStrings(\"read write\", \"\", \"delete\")).toBe(\"read write delete\");\n});\n\nexport function escapeTemplateLiteral(s: string): string {\n return s.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll(\"`\", \"\\\\`\").replaceAll(\"${\", \"\\\\${\");\n}\nundefined?.test(\"escapeTemplateLiteral\", ({ expect }) => {\n // Test with empty string\n expect(escapeTemplateLiteral(\"\")).toBe(\"\");\n\n // Test with normal string (no special characters)\n expect(escapeTemplateLiteral(\"hello world\")).toBe(\"hello world\");\n\n // Test with backtick\n const input1 = \"hello `world`\";\n const output1 = escapeTemplateLiteral(input1);\n // Verify backticks are escaped\n expect(output1).toBe(\"hello \\\\`world\\\\`\");\n\n // Test with backslash\n const input2 = \"hello \\\\world\";\n const output2 = escapeTemplateLiteral(input2);\n // Verify backslashes are escaped\n expect(output2).toBe(\"hello \\\\\\\\world\");\n\n // Test with dollar sign\n const input3 = \"hello $world\";\n const output3 = escapeTemplateLiteral(input3);\n // Verify dollar signs are escaped\n expect(output3).toBe(\"hello $world\");\n\n // Test with dollar sign in interpolation\n const input4 = \"hello ${$world\";\n const output4 = escapeTemplateLiteral(input4);\n // Verify dollar signs are escaped\n expect(output4).toBe(\"hello \\\\${$world\");\n\n // Test with multiple special characters\n const input5 = \"`hello` ${world\\\\\";\n const output5 = escapeTemplateLiteral(input5);\n // Verify all special characters are escaped\n expect(output5).toBe(\"\\\\`hello\\\\` \\\\${world\\\\\\\\\");\n\n // Test with already escaped characters\n const input6 = \"\\\\`hello\\\\`\";\n const output6 = escapeTemplateLiteral(input6);\n expect(output6).toBe(\"\\\\\\\\\\\\`hello\\\\\\\\\\\\`\");\n});\n\n/**\n * Some classes have different constructor names in different environments (eg. `Headers` is sometimes called `_Headers`,\n * so we create an object of overrides to handle these cases.\n */\nconst nicifiableClassNameOverrides = new Map(Object.entries({\n Headers,\n} as Record<string, unknown>).map(([k, v]) => [v, k]));\nexport type Nicifiable = {\n getNicifiableKeys?(): PropertyKey[],\n getNicifiedObjectExtraLines?(): string[],\n};\nexport type NicifyOptions = {\n maxDepth: number,\n currentIndent: string,\n lineIndent: string,\n multiline: boolean,\n refs: Map<unknown, string>,\n path: string,\n parent: null | {\n options: NicifyOptions,\n value: unknown,\n },\n keyInParent: PropertyKey | null,\n hideFields: PropertyKey[],\n overrides: (...args: Parameters<typeof nicify>) => string | null,\n};\nexport function nicify(\n value: unknown,\n options: Partial<NicifyOptions> = {},\n): string {\n const fullOptions: NicifyOptions = {\n maxDepth: 5,\n currentIndent: \"\",\n lineIndent: \" \",\n multiline: true,\n refs: new Map(),\n path: \"value\",\n parent: null,\n overrides: () => null,\n keyInParent: null,\n hideFields: [],\n ...filterUndefined(options),\n };\n const {\n maxDepth,\n currentIndent,\n lineIndent,\n multiline,\n refs,\n path,\n overrides,\n hideFields,\n } = fullOptions;\n const nl = `\\n${currentIndent}`;\n\n const overrideResult = overrides(value, options);\n if (overrideResult !== null) return overrideResult;\n\n if ([\"function\", \"object\", \"symbol\"].includes(typeof value) && value !== null) {\n if (refs.has(value)) {\n return `Ref<${refs.get(value)}>`;\n }\n refs.set(value, path);\n }\n\n const newOptions: NicifyOptions = {\n maxDepth: maxDepth - 1,\n currentIndent,\n lineIndent,\n multiline,\n refs,\n path: path + \"->[unknown property]\",\n overrides,\n parent: { value, options: fullOptions },\n keyInParent: null,\n hideFields: [],\n };\n const nestedNicify = (newValue: unknown, newPath: string, keyInParent: PropertyKey | null, options: Partial<NicifyOptions> = {}) => {\n return nicify(newValue, {\n ...newOptions,\n path: newPath,\n currentIndent: currentIndent + lineIndent,\n keyInParent,\n ...options,\n });\n };\n\n switch (typeof value) {\n case \"boolean\": case \"number\": {\n return JSON.stringify(value);\n }\n case \"string\": {\n const isDeindentable = (v: string) => deindent(v) === v && v.includes(\"\\n\");\n const wrapInDeindent = (v: string) => deindent`\n deindent\\`\n ${currentIndent + lineIndent}${escapeTemplateLiteral(v).replaceAll(\"\\n\", nl + lineIndent)}\n ${currentIndent}\\`\n `;\n if (isDeindentable(value)) {\n return wrapInDeindent(value);\n } else if (value.endsWith(\"\\n\") && isDeindentable(value.slice(0, -1))) {\n return wrapInDeindent(value.slice(0, -1)) + ' + \"\\\\n\"';\n } else {\n return JSON.stringify(value);\n }\n }\n case \"undefined\": {\n return \"undefined\";\n }\n case \"symbol\": {\n return value.toString();\n }\n case \"bigint\": {\n return `${value}n`;\n }\n case \"function\": {\n if (value.name) return `function ${value.name}(...) { ... }`;\n return `(...) => { ... }`;\n }\n case \"object\": {\n if (value === null) return \"null\";\n if (Array.isArray(value)) {\n const extraLines = getNicifiedObjectExtraLines(value);\n const resValueLength = value.length + extraLines.length;\n if (resValueLength === 0) return \"[]\"; // early return in case maxDepth <= 0\n if (maxDepth <= 0) return `[...]`;\n const resValues = value.map((v, i) => nestedNicify(v, `${path}[${i}]`, i));\n resValues.push(...extraLines);\n if (resValues.length !== resValueLength) throw new StackAssertionError(\"nicify of object: resValues.length !== resValueLength\", { value, resValues, resValueLength });\n const shouldIndent = resValues.length > 4 || resValues.some(x => (resValues.length > 1 && x.length > 4) || x.includes(\"\\n\"));\n if (shouldIndent) {\n return `[${nl}${resValues.map(x => `${lineIndent}${x},${nl}`).join(\"\")}]`;\n } else {\n return `[${resValues.join(\", \")}]`;\n }\n }\n if (value instanceof Date) {\n return `Date(${nestedNicify(value.toISOString(), `${path}.toISOString()`, null)})`;\n }\n if (value instanceof URL) {\n return `URL(${nestedNicify(value.toString(), `${path}.toString()`, null)})`;\n }\n if (ArrayBuffer.isView(value)) {\n return `${value.constructor.name}([${value.toString()}])`;\n }\n if (value instanceof ArrayBuffer) {\n return `ArrayBuffer [${new Uint8Array(value).toString()}]`;\n }\n if (value instanceof Error) {\n let stack = value.stack ?? \"\";\n const toString = value.toString();\n if (!stack.startsWith(toString)) stack = `${toString}\\n${stack}`; // some browsers don't include the error message in the stack, some do\n stack = stack.trimEnd();\n stack = stack.replace(/\\n\\s+/g, `\\n${lineIndent}${lineIndent}`);\n stack = stack.replace(\"\\n\", `\\n${lineIndent}Stack:\\n`);\n if (Object.keys(value).length > 0) {\n stack += `\\n${lineIndent}Extra properties: ${nestedNicify(Object.fromEntries(Object.entries(value)), path, null)}`;\n }\n if (value.cause) {\n stack += `\\n${lineIndent}Cause:\\n${lineIndent}${lineIndent}${nestedNicify(value.cause, path, null, { currentIndent: currentIndent + lineIndent + lineIndent })}`;\n }\n stack = stack.replaceAll(\"\\n\", `\\n${currentIndent}`);\n return stack;\n }\n\n const constructorName = [null, Object.prototype].includes(Object.getPrototypeOf(value)) ? null : (nicifiableClassNameOverrides.get(value.constructor) ?? value.constructor.name);\n const constructorString = constructorName ? `${constructorName} ` : \"\";\n\n const entries = getNicifiableEntries(value).filter(([k]) => !hideFields.includes(k));\n const extraLines = [\n ...getNicifiedObjectExtraLines(value),\n ...hideFields.length > 0 ? [`<some fields may have been hidden>`] : [],\n ];\n const resValueLength = entries.length + extraLines.length;\n if (resValueLength === 0) return `${constructorString}{}`;\n if (maxDepth <= 0) return `${constructorString}{ ... }`;\n const resValues = entries.map(([k, v], keyIndex) => {\n const keyNicified = nestedNicify(k, `Object.keys(${path})[${keyIndex}]`, null);\n const keyInObjectLiteral = typeof k === \"string\" ? nicifyPropertyString(k) : `[${keyNicified}]`;\n if (typeof v === \"function\" && v.name === k) {\n return `${keyInObjectLiteral}(...): { ... }`;\n } else {\n return `${keyInObjectLiteral}: ${nestedNicify(v, `${path}[${keyNicified}]`, k)}`;\n }\n });\n resValues.push(...extraLines);\n if (resValues.length !== resValueLength) throw new StackAssertionError(\"nicify of object: resValues.length !== resValueLength\", { value, resValues, resValueLength });\n const shouldIndent = resValues.length > 1 || resValues.some(x => x.includes(\"\\n\"));\n\n if (resValues.length === 0) return `${constructorString}{}`;\n if (shouldIndent) {\n return `${constructorString}{${nl}${resValues.map(x => `${lineIndent}${x},${nl}`).join(\"\")}}`;\n } else {\n return `${constructorString}{ ${resValues.join(\", \")} }`;\n }\n }\n default: {\n return `${typeof value}<${value}>`;\n }\n }\n}\n\nexport function replaceAll(input: string, searchValue: string, replaceValue: string): string {\n if (searchValue === \"\") throw new StackAssertionError(\"replaceAll: searchValue is empty\");\n return input.split(searchValue).join(replaceValue);\n}\nundefined?.test(\"replaceAll\", ({ expect }) => {\n expect(replaceAll(\"hello world\", \"o\", \"x\")).toBe(\"hellx wxrld\");\n expect(replaceAll(\"aaa\", \"a\", \"b\")).toBe(\"bbb\");\n expect(replaceAll(\"\", \"a\", \"b\")).toBe(\"\");\n expect(replaceAll(\"abc\", \"b\", \"\")).toBe(\"ac\");\n expect(replaceAll(\"test.test.test\", \".\", \"_\")).toBe(\"test_test_test\");\n expect(replaceAll(\"a.b*c\", \".\", \"x\")).toBe(\"axb*c\");\n expect(replaceAll(\"a*b*c\", \"*\", \"x\")).toBe(\"axbxc\");\n expect(replaceAll(\"hello hello\", \"hello\", \"hi\")).toBe(\"hi hi\");\n});\n\nfunction nicifyPropertyString(str: string) {\n return JSON.stringify(str);\n}\nundefined?.test(\"nicifyPropertyString\", ({ expect }) => {\n // Test valid identifiers\n expect(nicifyPropertyString(\"validName\")).toBe('\"validName\"');\n expect(nicifyPropertyString(\"_validName\")).toBe('\"_validName\"');\n expect(nicifyPropertyString(\"valid123Name\")).toBe('\"valid123Name\"');\n\n // Test invalid identifiers\n expect(nicifyPropertyString(\"123invalid\")).toBe('\"123invalid\"');\n expect(nicifyPropertyString(\"invalid-name\")).toBe('\"invalid-name\"');\n expect(nicifyPropertyString(\"invalid space\")).toBe('\"invalid space\"');\n expect(nicifyPropertyString(\"$invalid\")).toBe('\"$invalid\"');\n expect(nicifyPropertyString(\"\")).toBe('\"\"');\n\n // Test with special characters\n expect(nicifyPropertyString(\"property!\")).toBe('\"property!\"');\n expect(nicifyPropertyString(\"property.name\")).toBe('\"property.name\"');\n\n // Test with escaped characters\n expect(nicifyPropertyString(\"\\\\\")).toBe('\"\\\\\\\\\"');\n expect(nicifyPropertyString('\"')).toBe('\"\\\\\"\"');\n});\n\nfunction getNicifiableKeys(value: Nicifiable | object) {\n const overridden = (\"getNicifiableKeys\" in value ? value.getNicifiableKeys?.bind(value) : null)?.();\n if (overridden != null) return overridden;\n if (value instanceof Response) {\n return ['status', 'headers'];\n }\n const keys = Object.keys(value).sort();\n return unique(keys);\n}\nundefined?.test(\"getNicifiableKeys\", ({ expect }) => {\n // Test regular object\n expect(getNicifiableKeys({ b: 1, a: 2, c: 3 })).toEqual([\"a\", \"b\", \"c\"]);\n\n // Test empty object\n expect(getNicifiableKeys({})).toEqual([]);\n\n\n expect(getNicifiableKeys(new Response())).toEqual([\"status\", \"headers\"]);\n\n // Test object with custom getNicifiableKeys\n const customObject = {\n a: 1,\n b: 2,\n getNicifiableKeys() {\n return [\"customKey1\", \"customKey2\"];\n }\n };\n expect(getNicifiableKeys(customObject)).toEqual([\"customKey1\", \"customKey2\"]);\n});\n\nfunction getNicifiableEntries(value: Nicifiable | object): [PropertyKey, unknown][] {\n const recordLikes = [Headers];\n function isRecordLike(value: unknown): value is InstanceType<typeof recordLikes[number]> {\n return recordLikes.some(x => value instanceof x);\n }\n\n if (isRecordLike(value)) {\n return [...value.entries()].sort(([a], [b]) => stringCompare(`${a}`, `${b}`));\n }\n const keys = getNicifiableKeys(value);\n return keys.map((k) => [k, value[k as never]] as [PropertyKey, unknown]);\n}\n\nfunction getNicifiedObjectExtraLines(value: Nicifiable | object) {\n return (\"get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