💚 End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Use shared base media and utils in albums
Anand Baburajane8c5e82c0dd1
diff --git a/web/apps/albums/next.config.js b/web/apps/albums/next.config.jsindex effb7ea550..5a52794ab2 100644--- a/web/apps/albums/next.config.js+++ b/web/apps/albums/next.config.js@@ -1,42 +1 @@-// @ts-check--const cp = require("child_process");-const path = require("path");--const gitSHA = (() => {- const result = cp- .execSync("git rev-parse --short HEAD 2>/dev/null || true", {- cwd: __dirname,- encoding: "utf8",- })- .trimEnd();- return result || undefined;-})();--const appName = path.basename(process.cwd());--/** @type {import("next").NextConfig} */-module.exports = {- output: "export",- devIndicators: false,- compiler: { emotion: true },- env: {- gitSHA,- appName,- },- webpack: (config, { isServer }) => {- if (!isServer) {- config.resolve.fallback.fs = false;- }-- config.ignoreWarnings = [{ module: /libheif-js/ }];- config.experiments = { ...config.experiments, asyncWebAssembly: true };- config.output = config.output || {};- config.output.environment = {- ...(config.output.environment || {}),- asyncFunction: true,- };-- return config;- },-};+module.exports = require("ente-base/next.config.base.js");diff --git a/web/apps/albums/package.json b/web/apps/albums/package.jsonindex 4646fa6b6d..7d1dfb8b05 100644--- a/web/apps/albums/package.json+++ b/web/apps/albums/package.json@@ -16,6 +16,9 @@"comlink": "^4.4.2","dayjs": "^1.11.18","debounce": "^2.2.0",+ "ente-base": "*",+ "ente-media": "*",+ "ente-utils": "*","exifreader": "^4.32.0","file-type": "21.3.1","formik": "^2.4.6",@@ -53,6 +56,7 @@"@types/node": "^22.15.32","@types/react": "^19.2.2","@types/react-dom": "^19.2.2",- "@types/react-window": "^1.8.8"+ "@types/react-window": "^1.8.8",+ "ente-build-config": "*"}}diff --git a/web/apps/albums/src/pages/_app.tsx b/web/apps/albums/src/pages/_app.tsxindex 998e58a358..551fdcb168 100644--- a/web/apps/albums/src/pages/_app.tsx+++ b/web/apps/albums/src/pages/_app.tsx@@ -16,7 +16,7 @@ import { useLoadingBar } from "ente-new/photos/components/utils/use-loading-bar"import { PhotosAppContext } from "ente-new/photos/types/context";import { t } from "i18next";import type { AppProps } from "next/app";-import { useMemo } from "react";+import { useCallback, useMemo } from "react";import "photoswipe/dist/photoswipe.css";import "styles/global.css";@@ -29,10 +29,13 @@ const App: React.FC<AlbumsAppProps> = ({ Component, pageProps }) => {const { showMiniDialog, miniDialogProps } = useAttributedMiniDialog();const { showNotification, notificationProps } = useNotification();const { loadingBarRef, showLoadingBar, hideLoadingBar } = useLoadingBar();+ const logout = useCallback(() => {+ // Public albums does not maintain a logged-in app session.+ }, []);const baseContext = useMemo(- () => deriveBaseContext({ showMiniDialog }),- [showMiniDialog],+ () => deriveBaseContext({ logout, showMiniDialog }),+ [logout, showMiniDialog],);const appContext = useMemo(() => ({diff --git a/web/apps/albums/tsconfig.json b/web/apps/albums/tsconfig.jsonindex d3f5405c2e..cff1fffd8b 100644--- a/web/apps/albums/tsconfig.json+++ b/web/apps/albums/tsconfig.json@@ -1,25 +1,6 @@{+ "extends": "ente-build-config/tsconfig-next.json","compilerOptions": {- "noEmit": true,- "lib": ["ESnext", "DOM", "DOM.Iterable", "WebWorker"],- "target": "ES2020",- "module": "ESNext",- "moduleResolution": "bundler",- "jsx": "preserve",- "isolatedModules": true,- "esModuleInterop": true,- "skipLibCheck": true,- "verbatimModuleSyntax": true,- "resolveJsonModule": true,- "strict": true,- "noImplicitReturns": true,- "noUnusedParameters": true,- "noUnusedLocals": true,- "noFallthroughCasesInSwitch": true,- "noUncheckedIndexedAccess": true,- "exactOptionalPropertyTypes": false,- "allowJs": true,- "incremental": true,"baseUrl": ".","paths": {"components/*": ["vendor/photos/components/*"],@@ -27,11 +8,8 @@"services/*": ["vendor/photos/services/*"],"utils/*": ["vendor/photos/utils/*"],"styles/*": ["vendor/photos/styles/*"],- "ente-base/*": ["vendor/ente-base/*"],"ente-gallery/*": ["vendor/ente-gallery/*"],- "ente-media/*": ["vendor/ente-media/*"],- "ente-new/*": ["vendor/ente-new/*"],- "ente-utils/*": ["vendor/ente-utils/*"]+ "ente-new/*": ["vendor/ente-new/*"]}},"include": [@@ -42,7 +20,9 @@"vendor/**/*.ts","vendor/**/*.tsx","vendor/**/*.js",- "vendor/**/*.d.ts"+ "vendor/**/*.d.ts",+ "../../packages/base/components/utils/mui-theme.d.ts",+ "../../packages/base/global-electron.d.ts"],"exclude": ["node_modules", "out", ".next", ".next-desktop"]}diff --git a/web/apps/albums/vendor/ente-base/app.ts b/web/apps/albums/vendor/ente-base/app.tsdeleted file mode 100644index eb62cf33da..0000000000--- a/web/apps/albums/vendor/ente-base/app.ts+++ /dev/null@@ -1,19 +0,0 @@-export const appNames = [- "accounts",- "albums",- "auth",- "cast",- "embed",- "share",- "photos",- "ensu",- "locker",-] as const;--export type AppName = (typeof appNames)[number];--// This vendored copy only serves the public albums web app.-export const appName: AppName = "albums";-export const staticAppTitle = "Ente Photos";-export const clientPackageName = "io.ente.albums.web";-export const clientIdentifier = clientPackageName;diff --git a/web/apps/albums/vendor/ente-base/assert.ts b/web/apps/albums/vendor/ente-base/assert.tsdeleted file mode 100644index 6f4743e7db..0000000000--- a/web/apps/albums/vendor/ente-base/assert.ts+++ /dev/null@@ -1,15 +0,0 @@-import { isDevBuild } from "./env";-import log from "./log";--/**- * If running in a dev build, throw an exception with the given message.- * Otherwise log it as a warning.- *- * @param message An optional message to use for the failure. If not provided,- * then a generic one is used.- */-export const assertionFailed = (message?: string) => {- message = message ?? "Assertion failed";- if (isDevBuild) throw new Error(message);- log.warn(message);-};diff --git a/web/apps/albums/vendor/ente-base/blob-cache.ts b/web/apps/albums/vendor/ente-base/blob-cache.tsdeleted file mode 100644index c1b0b749a6..0000000000--- a/web/apps/albums/vendor/ente-base/blob-cache.ts+++ /dev/null@@ -1,43 +0,0 @@-const blobCacheNames = ["thumbs"] as const;--export type BlobCacheNamespace = (typeof blobCacheNames)[number];--export interface BlobCache {- get: (key: string) => Promise<Blob | undefined>;- has: (key: string) => Promise<boolean>;- put: (key: string, blob: Blob) => Promise<void>;- delete: (key: string) => Promise<boolean>;-}--const cachedCaches = new Map<BlobCacheNamespace, BlobCache>();--export const blobCache = async (- name: BlobCacheNamespace,-): Promise<BlobCache> => {- let cache = cachedCaches.get(name);- if (!cache) {- cache = await openBlobCache(name);- cachedCaches.set(name, cache);- }- return cache;-};--export const openBlobCache = async (- name: BlobCacheNamespace,-): Promise<BlobCache> => {- const cache = await caches.open(name);- return {- get: async (key: string) => {- const res = await cache.match(key);- return await res?.blob();- },- has: async (key: string) => !!(await cache.match(key)),- put: (key: string, blob: Blob) => cache.put(key, new Response(blob)),- delete: (key: string) => cache.delete(key),- };-};--export const clearBlobCaches = async () => {- cachedCaches.clear();- await Promise.all(blobCacheNames.map((name) => caches.delete(name)));-};diff --git a/web/apps/albums/vendor/ente-base/components/EnteLogo.tsx b/web/apps/albums/vendor/ente-base/components/EnteLogo.tsxdeleted file mode 100644index 1d77de41fc..0000000000--- a/web/apps/albums/vendor/ente-base/components/EnteLogo.tsx+++ /dev/null@@ -1,48 +0,0 @@-import { styled } from "@mui/material";-import React from "react";--interface EnteLogoProps {- /**- * The height of the logo image, in pixels.- *- * Default: 18px- */- height?: number;-}--/**- * The Ente logo ("ente" in Montserrat), as an inline SVG.- *- * Having it as an inline SVG has two advantages:- *- * - It does not rely on a corresponding asset in the public folder- * - It can be styled using CSS.- *- * The default height of the SVG element is 18px. The size can be customized by- * providing a {@link height} prop: the SVG will preserve its aspect ratio when- * fitting inside the provided viewport.- */-export const EnteLogo: React.FC<EnteLogoProps> = ({ height }) => (- <svg- height={height ?? "18"}- viewBox="0 0 43 13"- fill="currentColor"- xmlns="http://www.w3.org/2000/svg"- >- <path d="M6.102 12.144C4.998 12.144 4.026 11.928 3.186 11.496C2.358 11.064 1.716 10.476 1.26 9.732C0.804 8.976 0.576 8.118 0.576 7.158C0.576 6.186 0.798 5.328 1.242 4.584C1.698 3.828 2.316 3.24 3.096 2.82C3.876 2.388 4.758 2.172 5.742 2.172C6.69 2.172 7.542 2.376 8.298 2.784C9.066 3.18 9.672 3.756 10.116 4.512C10.56 5.256 10.782 6.15 10.782 7.194C10.782 7.302 10.776 7.428 10.764 7.572C10.752 7.704 10.74 7.83 10.728 7.95H2.862V6.312H9.252L8.172 6.798C8.172 6.294 8.07 5.856 7.866 5.484C7.662 5.112 7.38 4.824 7.02 4.62C6.66 4.404 6.24 4.296 5.76 4.296C5.28 4.296 4.854 4.404 4.482 4.62C4.122 4.824 3.84 5.118 3.636 5.502C3.432 5.874 3.33 6.318 3.33 6.834V7.266C3.33 7.794 3.444 8.262 3.672 8.67C3.912 9.066 4.242 9.372 4.662 9.588C5.094 9.792 5.598 9.894 6.174 9.894C6.69 9.894 7.14 9.816 7.524 9.66C7.92 9.504 8.28 9.27 8.604 8.958L10.098 10.578C9.654 11.082 9.096 11.472 8.424 11.748C7.752 12.012 6.978 12.144 6.102 12.144ZM18.5375 2.172C19.3055 2.172 19.9895 2.328 20.5895 2.64C21.2015 2.94 21.6815 3.408 22.0295 4.044C22.3775 4.668 22.5515 5.472 22.5515 6.456V12H19.7435V6.888C19.7435 6.108 19.5695 5.532 19.2215 5.16C18.8855 4.788 18.4055 4.602 17.7815 4.602C17.3375 4.602 16.9355 4.698 16.5755 4.89C16.2275 5.07 15.9515 5.352 15.7475 5.736C15.5555 6.12 15.4595 6.612 15.4595 7.212V12H12.6515V2.316H15.3335V4.998L14.8295 4.188C15.1775 3.54 15.6755 3.042 16.3235 2.694C16.9715 2.346 17.7095 2.172 18.5375 2.172ZM29.0568 12.144C27.9168 12.144 27.0288 11.856 26.3928 11.28C25.7568 10.692 25.4388 9.822 25.4388 8.67V0.174H28.2468V8.634C28.2468 9.042 28.3548 9.36 28.5708 9.588C28.7868 9.804 29.0808 9.912 29.4528 9.912C29.8968 9.912 30.2748 9.792 30.5868 9.552L31.3428 11.532C31.0548 11.736 30.7068 11.892 30.2988 12C29.9028 12.096 29.4888 12.144 29.0568 12.144ZM23.9448 4.692V2.532H30.6588V4.692H23.9448ZM37.4262 12.144C36.3222 12.144 35.3502 11.928 34.5102 11.496C33.6822 11.064 33.0402 10.476 32.5842 9.732C32.1282 8.976 31.9002 8.118 31.9002 7.158C31.9002 6.186 32.1222 5.328 32.5662 4.584C33.0222 3.828 33.6402 3.24 34.4202 2.82C35.2002 2.388 36.0822 2.172 37.0662 2.172C38.0142 2.172 38.8662 2.376 39.6222 2.784C40.3902 3.18 40.9962 3.756 41.4402 4.512C41.8842 5.256 42.1062 6.15 42.1062 7.194C42.1062 7.302 42.1002 7.428 42.0882 7.572C42.0762 7.704 42.0642 7.83 42.0522 7.95H34.1862V6.312H40.5762L39.4962 6.798C39.4962 6.294 39.3942 5.856 39.1902 5.484C38.9862 5.112 38.7042 4.824 38.3442 4.62C37.9842 4.404 37.5642 4.296 37.0842 4.296C36.6042 4.296 36.1782 4.404 35.8062 4.62C35.4462 4.824 35.1642 5.118 34.9602 5.502C34.7562 5.874 34.6542 6.318 34.6542 6.834V7.266C34.6542 7.794 34.7682 8.262 34.9962 8.67C35.2362 9.066 35.5662 9.372 35.9862 9.588C36.4182 9.792 36.9222 9.894 37.4982 9.894C38.0142 9.894 38.4642 9.816 38.8482 9.66C39.2442 9.504 39.6042 9.27 39.9282 8.958L41.4222 10.578C40.9782 11.082 40.4202 11.472 39.7482 11.748C39.0762 12.012 38.3022 12.144 37.4262 12.144Z" />- </svg>-);--/**- * A container for {@link EnteLogo} that reset the line height to vertically- * center the logo within the surrounding context.- *- * By default, the line height causes the SVG to have an extra space at the- * bottom. Removing it allows the SVG contents to be centered using its inherent- * sizing. his is a convenience container that resets the line height, and also- * takes the {@link sx} prop to allow for easy tweaking of other styling of the- * container without touching the SVG.- */-export const EnteLogoBox = styled("div")`- line-height: 0;-`;diff --git a/web/apps/albums/vendor/ente-base/components/EnteSwitch.tsx b/web/apps/albums/vendor/ente-base/components/EnteSwitch.tsxdeleted file mode 100644index b339fafecb..0000000000--- a/web/apps/albums/vendor/ente-base/components/EnteSwitch.tsx+++ /dev/null@@ -1,55 +0,0 @@-import { Switch, styled, type SwitchProps } from "@mui/material";-import React from "react";--/**- * A custom variant of the MUI {@link Switch}, styled per our designs.- */-export const EnteSwitch: React.FC<SwitchProps> = styled((props) => (- <Switch disableRipple {...props} />-))(({ theme }) => ({- width: 40,- height: 24,- padding: 0,- "& .MuiSwitch-switchBase": {- padding: 0,- margin: 2,- transitionDuration: "300ms",- "&.Mui-checked": {- transform: "translateX(16px)",- color: "white",- "& + .MuiSwitch-track": {- opacity: 1,- border: 0,- backgroundColor: theme.vars.palette.fixed.switchOn,- },- "&.Mui-disabled + .MuiSwitch-track": { opacity: 0.5 },- },- "&.Mui-disabled .MuiSwitch-thumb": {- color: theme.vars.palette.grey[600],- ...theme.applyStyles("light", {- color: theme.vars.palette.grey[100],- }),- },- "&.Mui-disabled + .MuiSwitch-track": { opacity: 0.3 },- },- "& .MuiSwitch-thumb": { boxSizing: "border-box", width: 20, height: 20 },- "& .MuiSwitch-track": {- borderRadius: 22 / 2,- backgroundColor: theme.vars.palette.fill.muted,- opacity: 1,- transition: theme.transitions.create(["background-color"], {- duration: 500,- }),- },- // Use an alternative affordance to indicate focusVisible as the ripple- // effect is disabled.- ".MuiSwitch-switchBase.Mui-focusVisible + .MuiSwitch-track": {- outline: `2px solid ${theme.vars.palette.stroke.muted}`,- outlineOffset: "-2px",- },- // Same for when the switch is active.- ".MuiSwitch-switchBase:active + .MuiSwitch-track": {- outline: `1px solid ${theme.vars.palette.stroke.faint}`,- outlineOffset: "-1px",- },-}));diff --git a/web/apps/albums/vendor/ente-base/components/ErrorIndicator.tsx b/web/apps/albums/vendor/ente-base/components/ErrorIndicator.tsxdeleted file mode 100644index 16f7ebf919..0000000000--- a/web/apps/albums/vendor/ente-base/components/ErrorIndicator.tsx+++ /dev/null@@ -1,41 +0,0 @@-import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";-import { Stack, Typography } from "@mui/material";-import { t } from "i18next";-import type React from "react";--/**- * An error message indicator, styled to complement {@link ActivityIndicator}.- *- * If a child is provided, it is used as the error message to show (after being- * wrapped in a suitable {@link Typography}). Otherwise the default generic- * error message is shown.- */-export const ActivityErrorIndicator: React.FC<React.PropsWithChildren> = ({- children,-}) => (- <Stack sx={{ gap: 2, alignItems: "center" }}>- <ErrorOutlineIcon color="secondary" />- <Typography sx={{ color: "text.muted" }}>- {children ?? t("generic_error")}- </Typography>- </Stack>-);--/**- * An smaller error message indicator suitable for being shown above or below- * text fields.- *- * If a child is provided, it is used as the error message to show (after being- * wrapped in a suitable {@link Typography}). Otherwise the default generic- * error message is shown.- */-export const InlineErrorIndicator: React.FC<React.PropsWithChildren> = ({- children,-}) => (- <Stack direction="row" sx={{ gap: "5px", alignItems: "center" }}>- <ErrorOutlineIcon sx={{ fontSize: "16px", color: "critical.main" }} />- <Typography variant="small" sx={{ color: "critical.main" }}>- {children ?? t("generic_error")}- </Typography>- </Stack>-);diff --git a/web/apps/albums/vendor/ente-base/components/Head.tsx b/web/apps/albums/vendor/ente-base/components/Head.tsxdeleted file mode 100644index 15d9e07d6b..0000000000--- a/web/apps/albums/vendor/ente-base/components/Head.tsx+++ /dev/null@@ -1,53 +0,0 @@-import Head from "next/head";-import React from "react";-import { haveWindow } from "../env";-import { albumsAppOrigin, isCustomAlbumsAppOrigin } from "../origins";--interface CustomHeadProps {- title: string;-}--export const CustomHead: React.FC<CustomHeadProps> = ({ title }) => (- <Head>- <title>{title}</title>- <link rel="icon" href="/images/favicon.png" type="image/png" />- <meta- name="description"- content="Ente - end-to-end encrypted cloud with open-source apps"- />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <meta name="referrer" content="strict-origin-when-cross-origin" />- </Head>-);--export const CustomHeadAlbums: React.FC = () => (- <Head>- <title>Ente Photos</title>- <link rel="icon" href="/images/favicon.png" type="image/png" />- <meta- name="description"- content="Safely store and share your best moments"- />- <meta- property="og:image"- content="https://albums.ente.io/images/preview.jpg"- />- <meta- name="twitter:image"- content="https://albums.ente.io/images/preview.jpg"- />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <meta name="referrer" content="strict-origin-when-cross-origin" />- </Head>-);--export const CustomHeadPhotosOrAlbums: React.FC<CustomHeadProps> = ({- title,-}) =>- isCustomAlbumsAppOrigin ||- (haveWindow() &&- new URL(window.location.href).origin != albumsAppOrigin()) ? (- <CustomHead {...{ title }} />- ) : (- <CustomHeadAlbums />- );diff --git a/web/apps/albums/vendor/ente-base/components/LinkButton.tsx b/web/apps/albums/vendor/ente-base/components/LinkButton.tsxdeleted file mode 100644index cd7be3fd57..0000000000--- a/web/apps/albums/vendor/ente-base/components/LinkButton.tsx+++ /dev/null@@ -1,54 +0,0 @@-import { Link, type ButtonProps } from "@mui/material";-import React from "react";--/**- * A button that looks like a link.- *- * The use of this component is not encouraged. It is only useful in uncommon- * cases where we do not have sufficient space to include a proper button.- */-export const LinkButton: React.FC<- React.PropsWithChildren<Pick<ButtonProps, "onClick">>-> = ({ onClick, children }) => (- <Link- component="button"- sx={(theme) => ({- color: "text.base",- textDecoration: "underline",- // The shortcut "text.faint" does not work with textDecorationColor- // (as of MUI v6).- textDecorationColor: theme.vars.palette.text.faint,- "&:hover": {- color: "accent.main",- textDecoration: "underline",- textDecorationColor: "accent.main",- },- })}- {...{ onClick }}- >- {children}- </Link>-);--/**- * A variant of {@link LinkButton} that does not show an underline, and instead- * uses a bolder font weight to indicate clickability.- *- * Similar caveats as {@link LinkButton} apply.- */-export const LinkButtonUndecorated: React.FC<- React.PropsWithChildren<Pick<ButtonProps, "onClick">>-> = ({ onClick, children }) => (- <Link- component="button"- sx={{- textDecoration: "none",- color: "text.muted",- fontWeight: "medium",- "&:hover": { color: "accent.main" },- }}- {...{ onClick }}- >- {children}- </Link>-);diff --git a/web/apps/albums/vendor/ente-base/components/MiniDialog.tsx b/web/apps/albums/vendor/ente-base/components/MiniDialog.tsxdeleted file mode 100644index 21e48f17e1..0000000000--- a/web/apps/albums/vendor/ente-base/components/MiniDialog.tsx+++ /dev/null@@ -1,385 +0,0 @@-import type { ButtonProps, ModalProps } from "@mui/material";-import {- Box,- Dialog,- DialogContent,- DialogTitle,- Stack,- Typography,- type DialogProps,-} from "@mui/material";-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";-import { LoadingButton } from "ente-base/components/mui/LoadingButton";-import { t } from "i18next";-import React, { useState } from "react";-import log from "../log";-import { InlineErrorIndicator } from "./ErrorIndicator";--/**- * Customize the contents of an {@link AttributedMiniDialog}.- */-export interface MiniDialogAttributes {- /**- * The dialog's title.- *- * This will be usually be a string, but the prop accepts any React node to- * allow passing a i18next <Trans /> component.- */- title?: React.ReactNode;- /**- * An optional component shown next to the title.- */- icon?: React.ReactNode;- /**- * The dialog's message.- *- * This will be usually be a string, but the prop accepts any React node to- * allow passing a i18next <Trans /> component.- */- message?: React.ReactNode;- /**- * If `true`, then the dialog cannot be closed (e.g. with the ESC key, or- * clicking on the backdrop) except through one of the explicitly provided- * actions.- */- nonClosable?: boolean;- /**- * If `true`, then the dialog cannot be replaced by another dialog while it- * is being displayed.- *- * The app uses a single component to render mini dialogs, and it is- * possible that new dialog contents might preempt and replace contents in a- * dialog that is already being shown. Usually if such preemption is- * expected then both dialogs use differing mechanisms, but it can happen in- * rare unforeseen cases.- *- * This flag allow a dialog to indicate that it should not be preempted, as- * it contains some critical information.- *- * Use this flag sparingly.- */- nonReplaceable?: boolean;- /**- * Customize the primary action button shown in the dialog.- *- * This is provided by boxes which serve as some sort of confirmation. If- * not provided, only the {@link cancel} button is shown, unless that too is- * explicitly disabled.- */- continue?: {- /**- * The string to use as the label for the primary action button.- *- * Default is `t("ok")`.- */- text?: string;- /**- * The color of the button.- *- * Default is "accent".- */- color?: ButtonProps["color"];- /**- * If `true`, the primary action button is auto focused when the dialog- * is opened, allowing the user to confirm just by pressing ENTER.- */- autoFocus?: ButtonProps["autoFocus"];- /**- * The function to call when the user activates the button.- *- * If this function returns a promise, then an activity indicator will- * be shown on the button until the promise settles.- *- * If this function is not provided, or if the function completes /- * fulfills, then then the dialog is automatically closed.- *- * Otherwise (that is, if the provided function throws), the dialog- * remains open, showing a generic error.- *- * That's quite a mouthful, here's a flowchart:- *- * - Not provided: Close- * - Provided sync:- * - Success: Close- * - Failure: Remain open, showing generic error- * - Provided async:- * - Success: Close- * - Failure: Remain open, showing generic error- */- action?: () => void | Promise<void>;- };- /**- * Customize the secondary action button shown in the dialog.- *- * This is rarely needed. When provided, these attributes behave similar to- * the {@link continue} attributes, except this button is shown below the- * primary button.- *- * This is not supported when button direction is "row".- */- secondary?: {- /**- * The string to use as the label for the secondary action button.- *- * Must be provided.- */- text: string;- /**- * The color of the button.- *- * Default is "primary".- */- color?: ButtonProps["color"];- /**- * The function to call when the user activates the button.- *- * The behaviour of this function is exactly the same as that of the- * primary {@link action} provided via the {@link continue} attributes.- */- action?: () => void | Promise<void>;- };- /**- * The string to use as the label for the cancel button.- *- * Default is `t("cancel")`.- *- * Set this to `false` to omit the cancel button altogether.- *- * The object form allows providing both the button title and the action- * handler (synchronous). The dialog is always closed on clicks.- */- cancel?: string | false | { text: string; action: () => void };- /** The direction in which the buttons are stacked. Default is "column". */- buttonDirection?: "row" | "column";-}--type MiniDialogProps = Pick<DialogProps, "open"> & {- onClose: () => void;- attributes?: MiniDialogAttributes;-};--/**- * A small, mostly predefined, MUI {@link Dialog} that can be used to notify the- * user, or ask for confirmation before actions.- *- * The rendered dialog can be customized by modifying the {@link attributes}- * prop. If you find yourself wanting to customize it further, consider either- * using a {@link TitledMiniDialog} or {@link Dialog}.- */-export const AttributedMiniDialog: React.FC<- React.PropsWithChildren<MiniDialogProps>-> = ({ open, onClose, attributes, children }) => {- const [phase, setPhase] = useState<- "loading" | "secondary-loading" | "failed" | undefined- >();-- if (!attributes) {- return <></>;- }-- const resetPhaseAndClose = () => {- setPhase(undefined);- onClose();- };-- const handleClose: ModalProps["onClose"] = (_, reason) => {- if (attributes.nonClosable) return;- // Ignore backdrop clicks when we're processing the user request.- if (- reason == "backdropClick" &&- (phase == "loading" || phase == "secondary-loading")- ) {- return;- }- resetPhaseAndClose();- };-- const [cancelTitle, handleCancel] = ((- c: MiniDialogAttributes["cancel"],- ) => {- if (c === false) return [undefined, undefined];- if (c === undefined) return [t("cancel"), resetPhaseAndClose];- if (typeof c == "string") return [c, resetPhaseAndClose];- return [- c.text,- () => {- resetPhaseAndClose();- c.action();- },- ];- })(attributes.cancel);-- const loadingButton = attributes.continue && (- <LoadingButton- loading={phase == "loading"}- disabled={phase == "secondary-loading"}- fullWidth- color={attributes.continue.color ?? "accent"}- autoFocus={attributes.continue.autoFocus}- onClick={async () => {- setPhase("loading");- try {- await attributes.continue?.action?.();- resetPhaseAndClose();- } catch (e) {- log.error(e);- setPhase("failed");- }- }}- >- {attributes.continue.text ?? t("ok")}- </LoadingButton>- );-- const secondaryLoadingButton = attributes.secondary?.text && (- <LoadingButton- disabled={phase == "loading"}- loading={phase == "secondary-loading"}- fullWidth- color={attributes.secondary.color ?? "primary"}- onClick={async () => {- setPhase("secondary-loading");- try {- await attributes.secondary?.action?.();- resetPhaseAndClose();- } catch (e) {- log.error(e);- setPhase("failed");- }- }}- >- {attributes.secondary.text}- </LoadingButton>- );-- if (secondaryLoadingButton && attributes.buttonDirection == "row")- throw new Error("Unsupported combination");-- const cancelButton = cancelTitle && (- <FocusVisibleButton- fullWidth- color="secondary"- disabled={phase == "loading"}- onClick={handleCancel}- >- {cancelTitle}- </FocusVisibleButton>- );-- return (- <Dialog- {...{ open }}- onClose={handleClose}- fullWidth- slotProps={{ paper: { sx: { maxWidth: "360px" } } }}- >- {(attributes.icon ?? attributes.title) ? (- <Stack- direction="row"- sx={[- {- justifyContent: "space-between",- alignItems: "center",- "& > svg": {- fontSize: "32px",- color: "stroke.faint",- },- },- attributes.icon && attributes.title- ? { padding: "20px 16px 0px 16px" }- : { padding: "24px 16px 4px 16px" },- ]}- >- {attributes.title && (- <DialogTitle- sx={{- "&&&": { padding: 0 },- // Wrap the title to the next line if there- // isn't sufficient space to make it fit in one.- flexShrink: 1,- }}- >- {attributes.title}- </DialogTitle>- )}- {attributes.icon}- </Stack>- ) : (- <Box sx={{ height: "8px" }} /> /* Spacer */- )}- <DialogContent>- {attributes.message && (- <Typography- component={- typeof attributes.message == "string" ? "p" : "div"- }- sx={{ color: "text.muted" }}- >- {attributes.message}- </Typography>- )}- {children}- <Stack- sx={{ pt: 3, gap: 1 }}- direction={attributes.buttonDirection ?? "column"}- >- {phase == "failed" && <InlineErrorIndicator />}- {attributes.buttonDirection == "row" ? (- <>- {cancelButton}- {loadingButton}- </>- ) : (- <>- {loadingButton}- {secondaryLoadingButton}- {cancelButton}- </>- )}- </Stack>- </DialogContent>- </Dialog>- );-};--type TitledMiniDialogProps = Pick<DialogProps, "open" | "onClose" | "sx"> & {- /**- * The dialog's title.- */- title?: React.ReactNode;- /**- * Optional max width of the underlying MUI {@link Paper}.- *- * Default: 360px (same as {@link AttributedMiniDialog}).- */- paperMaxWidth?: string;-};--/**- * MiniDialog in a "shell" form.- *- * This is a {@link Dialog} for use at places which need more customization than- * what {@link AttributedMiniDialog} provides, but wish to retain a similar look- * and feel without duplicating code.- *- * It does three things:- *- * - Sets a fixed size and padding similar to {@link AttributedMiniDialog}.- * - Takes the title as a prop, and wraps it in a {@link DialogTitle}.- * - Wraps children in a scrollable {@link DialogContent}.- */-export const TitledMiniDialog: React.FC<- React.PropsWithChildren<TitledMiniDialogProps>-> = ({ open, onClose, sx, paperMaxWidth, title, children }) => (- <Dialog- {...{ open, sx }}- onClose={onClose}- fullWidth- slotProps={{ paper: { sx: { maxWidth: paperMaxWidth ?? "360px" } } }}- >- <DialogTitle sx={{ "&&&": { paddingBlock: "24px 16px" } }}>- {title}- </DialogTitle>- <DialogContent>{children}</DialogContent>- </Dialog>-);diff --git a/web/apps/albums/vendor/ente-base/components/Navbar.tsx b/web/apps/albums/vendor/ente-base/components/Navbar.tsxdeleted file mode 100644index 75edd810d5..0000000000--- a/web/apps/albums/vendor/ente-base/components/Navbar.tsx+++ /dev/null@@ -1,11 +0,0 @@-import { styled } from "@mui/material";--export const NavbarBase = styled("div")(- ({ theme }) => `- flex: 0 0 64px;- display: flex;- justify-content: center;- align-items: center;- border-bottom: 1px solid ${theme.vars.palette.divider};-`,-);diff --git a/web/apps/albums/vendor/ente-base/components/RowButton.tsx b/web/apps/albums/vendor/ente-base/components/RowButton.tsxdeleted file mode 100644index a66bec3e42..0000000000--- a/web/apps/albums/vendor/ente-base/components/RowButton.tsx+++ /dev/null@@ -1,425 +0,0 @@-import {- Box,- Divider,- Stack,- styled,- Typography,- type ButtonProps,- type TypographyProps,-} from "@mui/material";-import { EnteSwitch } from "ente-base/components/EnteSwitch";-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";-import React from "react";-import { ActivityIndicator } from "./mui/ActivityIndicator";--interface RowButtonGroupTitleProps {- /**- * An optional leading SvgIcon before the title.- */- icon?: React.ReactNode;-}--/**- * A section title, meant to precede a {@link RowButtonGroup}.- */-export const RowButtonGroupTitle: React.FC<- React.PropsWithChildren<RowButtonGroupTitleProps>-> = ({ children, icon }) => (- <Stack- direction="row"- sx={{- px: "8px",- py: "6px",- gap: "8px",- "& > svg": { fontSize: "17px", color: "stroke.muted" },- }}- >- {icon && icon}- <Typography variant="small" sx={{ color: "text.muted" }}>- {children}- </Typography>- </Stack>-);--/**- * A short description text meant to come after a {@link RowButtonGroup}.- */-export const RowButtonGroupHint: React.FC<React.PropsWithChildren> = ({- children,-}) => (- <Typography- variant="small"- sx={{ color: "text.faint", px: "16px", py: "6px" }}- >- {children}- </Typography>-);--/**- * A divider for buttons in a {@link RowButtonGroup}.- */-export const RowButtonDivider = () => (- <Divider sx={{ "&&&": { mttty: 0 }, opacity: 0.4 }} />-);--/**- * A group of {@link RowButton}s that visually look together as a single- * section.- *- * {@link RowButtonGroupTitle} can be used to provide a title for the entire- * group, and {@link RowButtonGroupHint} can be used to provide a hint text that- * follows the group.- *- * {@link RowButtonDivider} can be used to to separate the individual buttons in- * the group.- *- * ---- *- * Note: {@link RowButtonGroup} is not designed to work with the "secondary"- * variant of {@link RowButton}.- */-export const RowButtonGroup = styled("div")(- ({ theme }) => `- background-color: ${theme.vars.palette.fill.faint};- border-radius: 8px;- /* Modify the RowButton style when it is placed inside a RowButtonGroup. */- & > button {- border-radius: 8px;- background-color: transparent;- }- /* Need to retarget the disabled state with increased specificity. */- & > button.Mui-disabled {- background-color: transparent;- }- & > button:not(:last-of-type) {- border-bottom-left-radius: 0;- border-bottom-right-radius: 0;- }- & > button:not(:first-of-type) {- border-top-left-radius: 0;- border-top-right-radius: 0;- }- & > button:hover {- /* These fills are translucent and additive, and the RowButtonGroup- already has a background, so pick a (transparent) color that gives us- a similar outcome of the hover state as for a RowButton that is not- inside a RowButtonGroup */- background-color: ${theme.vars.palette.fill.faintHover};- }- /* Reset the border radius when showing focus outlines that will be added- by the styles attached to FocusVisibleButton. */- & > button.Mui-focusVisible {- border-radius: 8px;- }- /* Modify the outline offset added by FocusVisibleButton for a visual- effect that fits better with these row buttons. */- & > button:active {- outline-offset: 0;- }-`,-);--interface RowButtonProps {- /**- * Variants:- *- * - "primary" (default): A row button with a filled in background color.- *- * - "secondary": A row button without a fill.- */- variant?: "primary" | "secondary";- /**- * Color of the row button.- *- * Semantically, this is similar to the "color" props for a MUI button,- * except we only support two cases for this row button component:- *- * - "primary" (default): A row button that uses "text.base" as the color of- * the text (and an appropriate background color, if needed, based on the- * value of the {@link variant}).- *- * - "critical": A row button that uses "critical.main" as the color of the- * text. The background fill, if any, will be the same as what "primary"- * would've entailed.- */- color?: "primary" | "critical";- /**- * Modify the font weight of the {@link label}, when label is a string.- *- * Default: "medium".- */- fontWeight?: TypographyProps["fontWeight"];- /**- * If true, then the row button will be disabled.- */- disabled?: boolean;- /**- * Called when the row button is activated (e.g. by a click).- */- onClick: () => void;- /**- * Optional icon shown at the leading edge of the row button.- *- * This is usually an icon like an {@link SvgIcon}, but it can be any- * arbitrary component, the row button does not make any assumptions as to- * what this is.- *- * If it is an {@link SvgIcon}, the row button will size it appropriately.- */- startIcon?: React.ReactNode;- /**- * Optional icon shown at the trailing edge of the row button.- *- * Similar to {@link startIcon} this can be any arbitrary component, though- * usually it is an {@link SvgIcon} whose size the row button will set.- */- endIcon?: React.ReactNode;- /**- * The label for the component.- *- * Usually this is expected to be a string, in which case it is wrapped up- * in an appropriate {@link Typography} and shown on the row button. But it- * can be an arbitrary react component too, to allow customizing its- * appearance or otherwise modifying it in one off cases (it will be used as- * it is and not wrapped in a {@link Typography} if it is not a string).- */- label: React.ReactNode;- /**- * The text (or icon) to show alongside {@link label}, separated from it by- * a bullet.- *- * This is usually expected to be a string, in which case it is wrapped in a- * {@link Typography} component and styled with a muted text color before- * being rendered.- *- * However, it can also be an {@link SvgIcon} (or any an arbitrary- * component), though in terms of styling, only an {@link SvgIcon} usually- * makes sense.- *- * Similar to {@link label}, it will not be wrapped in a {@link Typography}- * if it is not a string.- */- caption?: React.ReactNode;-}--/**- * A button that looks like a row in a group of options / choices.- *- * It can be used both standalone, or as part of a {@link RowButtonGroup}.- */-export const RowButton: React.FC<RowButtonProps> = ({- variant = "primary",- color = "primary",- fontWeight = "medium",- disabled = false,- startIcon,- endIcon,- label,- caption,- onClick,-}) => (- <RowButtonRoot rbVariant={variant} fullWidth {...{ disabled, onClick }}>- <Stack- direction="row"- sx={[- {- flex: 1,- justifyContent: "space-between",- alignItems: "center",- px: "16px",- pr: "12px",- color: "text.base",- },- color == "critical" && { color: "critical.main" },- disabled && { color: "text.muted" },- ]}- >- <Stack- direction="row"- sx={{ py: "14px", gap: "10px", alignItems: "center" }}- >- {startIcon && startIcon}- <Box sx={{ px: "2px" }}>- {typeof label != "string" ? (- label- ) : caption ? (- <Stack- direction="row"- sx={{ gap: "4px", alignItems: "center" }}- >- {/* Don't shrink the main label, instead let the- caption grow into two lines if it needs to. */}- <Typography sx={{ flexShrink: 0 }}>- {label}- </Typography>- <CaptionTypography color={color}>- {"•"}- </CaptionTypography>- <CaptionTypography color={color}>- {caption}- </CaptionTypography>- </Stack>- ) : (- <Typography fontWeight={fontWeight}>{label}</Typography>- )}- </Box>- </Stack>- {endIcon && endIcon}- </Stack>- </RowButtonRoot>-);--type RowButtonRootProps = ButtonProps & {- // Prefix with "rb" to differentiate this from the "variant" prop of the MUI- // button that we're styling.- rbVariant: RowButtonProps["variant"];-};--const RowButtonRoot = styled(FocusVisibleButton, {- shouldForwardProp: (prop) => prop != "rbVariant",- // name: "MuiMenuItem",-})<React.PropsWithChildren<RowButtonRootProps>>(({ theme }) => ({- // Remove button's default padding.- padding: 0,- // Set the size of the any icons (SvgIcon instances) provided to us to make- // them fit with the Typography within the button's content.- "& .MuiSvgIcon-root": { fontSize: "20px" },- variants: [- {- props: { rbVariant: "primary" },- style: {- backgroundColor: theme.vars.palette.fill.faint,- "&:hover": { backgroundColor: theme.vars.palette.fill.muted },- },- },- {- props: { rbVariant: "secondary" },- style: {- backgroundColor: "transparent",- color: "white",- "&:hover": { backgroundColor: theme.vars.palette.fill.faint },- },- },- ],-}));--const CaptionTypography: React.FC<- React.PropsWithChildren<{ color: RowButtonProps["color"] }>-> = ({ color, children }) => (- <Typography- variant="small"- sx={[- color == "critical"- ? { color: "critical.main" }- : { color: "text.faint" },- ]}- >- {children}- </Typography>-);--interface RowSwitchProps {- /**- * The state of the contained {@link EnteSwitch}.- */- checked?: boolean;- /**- * Called when the user activates the contained {@link EnteSwitch}.- */- onClick: () => void;- /**- * The label for the component.- *- * Similar to the {@link label} prop for {@link RowButton}, but can only be- * a string instead of an arbitrary component.- */- label: string;-}--/**- * A row that visually looks similar to a {@link RowButton}, but instead of a- * button is a normal {@link Typography} with a {@link EnteSwitch} at its- * trailing edge.- *- * It only works (visually) when placed within a {@link RowButtonGroup} since- * that is where it gets its background color from.- */-export const RowSwitch: React.FC<RowSwitchProps> = ({- checked,- label,- onClick,-}) => (- <Stack- direction="row"- sx={{- flex: 1,- justifyContent: "space-between",- alignItems: "center",- px: "16px",- pr: "12px",- }}- >- <Typography sx={{ py: "14px", px: "2px", fontWeight: "medium" }}>- {label}- </Typography>- <EnteSwitch {...{ checked, onClick }} />- </Stack>-);--interface RowLabelProps {- /**- * Optional icon shown at the leading edge of the row button.- *- * This is usually an icon like an {@link SvgIcon}, but it can be any- * arbitrary component, the row button does not make any assumptions as to- * what this is.- *- * Unlike a {@link RowButton}, there is not sizing applied to it.- */- startIcon?: React.ReactNode;- /**- * The label for the component.- *- * Similar to the {@link label} prop for {@link RowButton}, but can only be- * a string instead of an arbitrary component.- */- label: string;-}--/**- * A row that visually looks similar to a {@link RowButton}, but instead of a- * button is a normal {@link Typography}.- *- * This is useful for creating non-interactive, static, labels.- *- * It only works (visually) when placed within a {@link RowButtonGroup} since- * that is where it gets its background color from.- */-export const RowLabel: React.FC<RowLabelProps> = ({ startIcon, label }) => (- <Stack- direction="row"- sx={{- flex: 1,- justifyContent: "space-between",- alignItems: "center",- px: "16px",- pr: "12px",- }}- >- <Stack direction="row" sx={{ py: "14px", gap: "10px" }}>- {startIcon && startIcon}- <Box sx={{ px: "2px" }}>- {/* Nb: Unlike the button, this has "regular" fontWeight. */}- <Typography>{label}</Typography>- </Box>- </Stack>- </Stack>-);--/**- * A variant of {@link ActivityIndicator} with defaults suitable to be used as the- * {@link EndIcon} of a {@link RowButton}.- */-export const RowButtonEndActivityIndicator: React.FC = () => (- <ActivityIndicator size="20px" sx={{ color: "stroke.muted" }} />-);diff --git a/web/apps/albums/vendor/ente-base/components/SingleInputForm.tsx b/web/apps/albums/vendor/ente-base/components/SingleInputForm.tsxdeleted file mode 100644index 24c4c24bb8..0000000000--- a/web/apps/albums/vendor/ente-base/components/SingleInputForm.tsx+++ /dev/null@@ -1,198 +0,0 @@-import {- Stack,- TextField,- type ButtonProps,- type TextFieldProps,-} from "@mui/material";-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";-import { LoadingButton } from "ente-base/components/mui/LoadingButton";-import log from "ente-base/log";-import { useFormik } from "formik";-import { t } from "i18next";-import React, { useCallback, useState } from "react";-import { ShowHidePasswordInputAdornment } from "./mui/PasswordInputAdornment";--export type SingleInputFormProps = Pick<- TextFieldProps,- "label" | "placeholder" | "autoComplete" | "autoFocus" | "slotProps"-> & {- /**- * The type attribute of the HTML input element that will be used.- *- * Default is "text".- *- * In addition to changing the behaviour of the HTML input element, the- * {@link SingleInputForm} component also has special casing for type- * "password", wherein it'll show an adornment at the end of the text field- * allowing the user to show or hide the password.- */- inputType?: TextFieldProps["type"];- /**- * The initial value, if any, to prefill in the input.- */- initialValue?: string;- /**- * Color of the submit button.- *- * Default: "accent".- */- submitButtonColor?: ButtonProps["color"];- /**- * Title for the submit button.- */- submitButtonTitle: string;- /**- * Cancellation handler.- *- * This function is called when the user activates the cancel button in the- * form.- *- * If this is not provided, then only a full width submit button will be- * shown in the form (below the input).- */- onCancel?: () => void;- /**- * Submission handler. A callback invoked when the submit button is pressed.- *- * During submission, the text input and the submit button are disabled, and- * an indeterminate progress indicator is shown.- *- * If this function rejects then a generic error helper text is shown below- * the text input, and the input (/ buttons) reenabled.- *- * This function is also passed an function that can be used to explicitly- * set the error message that as shown below the text input when a specific- * problem occurs during submission.- *- * @param name The current value of the text input.- *- * @param setFieldError A function that can be called to set the error message- * shown below the text input if submission fails.- *- * Note that if {@link setFieldError} is called, then the {@link onSubmit}- * function should not throw, otherwise the error message shown by- * {@link setFieldError} will get overwritten by the generic error message.- */- onSubmit:- | ((name: string, setFieldError: (message: string) => void) => void)- | ((- name: string,- setFieldError: (message: string) => void,- ) => Promise<void>);-};--/**- * A TextField and cancel/submit buttons.- *- * A common requirement is taking a single textual input from the user. This is- * a form suitable for that purpose. It contains a single MUI {@link TextField}- * and two accompanying buttons; one to submit, and one to cancel.- *- * Submission is handled as an async function, during which the input is- * disabled and a loading indicator is shown. Errors during submission are shown- * as the helper text associated with the text field.- *- * The input field in the form takes autoFocus automatically on mount. Turn off- * the {@link autoFocus} to disable this behaviour if needed.- */-export const SingleInputForm: React.FC<SingleInputFormProps> = ({- inputType,- initialValue,- autoFocus,- submitButtonTitle,- submitButtonColor,- onCancel,- onSubmit,- ...rest-}) => {- const [showPassword, setShowPassword] = useState(false);-- const handleToggleShowHidePassword = useCallback(- () => setShowPassword((show) => !show),- [],- );-- const formik = useFormik({- initialValues: { value: initialValue ?? "" },- onSubmit: async (values, { setFieldError }) => {- const value = values.value;- const setValueFieldError = (message: string) =>- setFieldError("value", message);-- if (!value) {- setValueFieldError(t("required"));- return;- }- try {- await onSubmit(value, setValueFieldError);- } catch (e) {- log.error(`Failed to submit input ${value}`, e);- setValueFieldError(t("generic_error"));- }- },- });-- const submitButton = (- <LoadingButton- fullWidth- type="submit"- loading={formik.isSubmitting}- color={submitButtonColor ?? "accent"}- >- {submitButtonTitle}- </LoadingButton>- );-- // [Note: Use space as default TextField helperText]- //- // For MUI text fields that use a conditional helperText, e.g. in case of- // errors, use an space as the default helperText in the other cases to- // avoid a layout shift when the helperText is conditionally shown.-- return (- <form onSubmit={formik.handleSubmit}>- <TextField- name="value"- value={formik.values.value}- onChange={formik.handleChange}- type={showPassword ? "text" : (inputType ?? "text")}- fullWidth- autoFocus={autoFocus ?? true}- margin="normal"- disabled={formik.isSubmitting}- error={!!formik.errors.value}- helperText={formik.errors.value ?? " "}- slotProps={{- input:- inputType == "password"- ? {- endAdornment: (- <ShowHidePasswordInputAdornment- showPassword={showPassword}- onToggle={- handleToggleShowHidePassword- }- />- ),- }- : {},- }}- {...rest}- />- {onCancel ? (- <Stack direction="row" sx={{ gap: "12px" }}>- <FocusVisibleButton- fullWidth- color="secondary"- onClick={onCancel}- >- {t("cancel")}- </FocusVisibleButton>- {submitButton}- </Stack>- ) : (- submitButton- )}- </form>- );-};diff --git a/web/apps/albums/vendor/ente-base/components/Typography.tsx b/web/apps/albums/vendor/ente-base/components/Typography.tsxdeleted file mode 100644index 9fa71e7b73..0000000000--- a/web/apps/albums/vendor/ente-base/components/Typography.tsx+++ /dev/null@@ -1,37 +0,0 @@-import { styled, Typography } from "@mui/material";--/**- * A variant of {@link Typography} that inserts ellipsis instead of wrapping the- * text over multiple lines, or letting it overflow.- *- * Refs:- * - https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_text/Wrapping_breaking_text- * - https://developer.mozilla.org/en-US/docs/Web/CSS/white-space- */-export const EllipsizedTypography = styled(Typography)`- /* Initial value of overflow is visible. Set overflow (the handling of- content that is too small for the container in the inline direction) to- hidden instead. */- overflow: hidden;- /* Specify handling of text when it overflows, asking the browser to insert- ellipsis instead of clipping.-- Note that both overflow and text-overflow are required.- */- text-overflow: ellipsis;- /* Don't automatically wrap the text by inserting line breaks. */- white-space: nowrap;-`;--/**- * A variant of {@link EllipsizedTypography} that takes up to 2 lines.- */-export const Ellipsized2LineTypography = styled(Typography)`- overflow: hidden;- text-overflow: ellipsis;- display: -webkit-box;- -webkit-line-clamp: 2; /* number of lines to show */- line-clamp: 2;- -webkit-box-orient: vertical;- word-break: break-word;-`;diff --git a/web/apps/albums/vendor/ente-base/components/containers.tsx b/web/apps/albums/vendor/ente-base/components/containers.tsxdeleted file mode 100644index d2ae57d3ad..0000000000--- a/web/apps/albums/vendor/ente-base/components/containers.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { Stack, styled } from "@mui/material";--/**- * A {@link Stack} that takes up at least the height of the entire viewport, and- * centers its children both vertically and horizontally.- */-export const Stack100vhCenter = styled(Stack)`- min-height: 100vh;- justify-content: center;- align-items: center;-`;--/**- * A flexbox with justify content set to space-between and item alignment set to- * center.- *- * There is also another SpaceBetweenFlex in the old shared package, but that- * one also sets width: 100%. As such, that one should be considered deprecated- * and its uses moved to this one when possible (so that we can then see where- * the width: 100% is essential).- */-export const SpacedRow = styled("div")`- display: flex;- justify-content: space-between;- align-items: center;-`;--/**- * A flexbox that shows its children after centering them both vertically and- * horizontally.- */-export const CenteredRow = styled("div")`- display: flex;- justify-content: center;- align-items: center;-`;--/**- * A flexbox that fills the entire flex direction, and shows its children after- * centering them both vertically and horizontally.- */-export const CenteredFill = styled("div")`- flex: 1;- display: flex;- justify-content: center;- align-items: center;-`;--/**- * An empty overlay on top of the nearest relative positioned ancestor.- *- * {@link Overlay} is an an absolute positioned div that fills the entire- * nearest relatively positioned ancestor. It is usually used in tandem with a- * derivate of {@link BaseTile} or {@link BaseTileButton} to show various- * indicators on top of thumbnails; but it can be used in any context where we- * want to overlay (usually) transparent content on top of a component.- *- * For filling much larger areas (e.g. showing a translucent overlay on top of- * the entire screen), use the MUI {@link Backdrop} instead.- */-export const Overlay = styled("div")`- position: absolute;- width: 100%;- height: 100%;- top: 0;- left: 0;-`;diff --git a/web/apps/albums/vendor/ente-base/components/loaders.tsx b/web/apps/albums/vendor/ente-base/components/loaders.tsxdeleted file mode 100644index 8e958c067e..0000000000--- a/web/apps/albums/vendor/ente-base/components/loaders.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { Backdrop } from "@mui/material";-import { Stack100vhCenter } from "ente-base/components/containers";-import { ActivityIndicator } from "ente-base/components/mui/ActivityIndicator";-import React from "react";--/**- * A centered activity indicator shown in a container that fills up the entire- * width and height of the viewport.- *- * This is meant as a root component of a page, e.g., during initial load.- */-export const LoadingIndicator: React.FC = () => (- <Stack100vhCenter>- <ActivityIndicator />- </Stack100vhCenter>-);--/**- * An translucent overlay that covers the entire viewport and shows an activity- * indicator in its center.- *- * Used as a overlay during blocking actions. The use of this component is not- * recommended for new code.- */-export const TranslucentLoadingOverlay: React.FC = () => (- <Backdrop- // Specifying open here causes us to lose animations. This is not- // optimal, but fine for now since this the use of this is limited to a- // few interstitial overlays, and if refactoring consider replacing this- // entirely with a more localized activity indicator.- open={true}- sx={{- backgroundColor: "var(--mui-palette-backdrop-muted)",- backdropFilter: "blur(30px) opacity(95%)",- /* Above the highest possible MUI z-index, that of the MUI tooltip- See: https://mui.com/material-ui/customization/default-theme/ */- zIndex: "calc(var(--mui-zIndex-tooltip) + 1)",- }}- >- <ActivityIndicator />- </Backdrop>-);diff --git a/web/apps/albums/vendor/ente-base/components/mui/ActivityIndicator.tsx b/web/apps/albums/vendor/ente-base/components/mui/ActivityIndicator.tsxdeleted file mode 100644index bd9e7620c2..0000000000--- a/web/apps/albums/vendor/ente-base/components/mui/ActivityIndicator.tsx+++ /dev/null@@ -1,29 +0,0 @@-import {- CircularProgress,- Stack,- Typography,- type CircularProgressProps,-} from "@mui/material";-import type React from "react";--/**- * A standard {@link CircularProgress} for use in our code.- *- * If a child is specified, it is wrapped in a Typography and shown as a caption- * below the {@link CircularProgress}.- *- * While it does take and forward props to the the underlying- * {@link CircularProgress}, if you find yourself needing to customize it too- * much, consider directly using a {@link CircularProgress} instead.- */-export const ActivityIndicator: React.FC<- React.PropsWithChildren<CircularProgressProps>-> = ({ children, ...rest }) =>- children ? (- <Stack sx={{ gap: 2, alignItems: "center" }}>- <CircularProgress color="accent" size={24} {...rest} />- <Typography sx={{ color: "text.muted" }}>{children}</Typography>- </Stack>- ) : (- <CircularProgress color="accent" size={32} {...rest} />- );diff --git a/web/apps/albums/vendor/ente-base/components/mui/DialogCloseIconButton.tsx b/web/apps/albums/vendor/ente-base/components/mui/DialogCloseIconButton.tsxdeleted file mode 100644index 6b8fc24856..0000000000--- a/web/apps/albums/vendor/ente-base/components/mui/DialogCloseIconButton.tsx+++ /dev/null@@ -1,22 +0,0 @@-import CloseIcon from "@mui/icons-material/Close";-import { IconButton } from "@mui/material";-import type { ModalVisibilityProps } from "ente-base/components/utils/modal";-import { t } from "i18next";-import React from "react";--type DialogCloseIconButtonProps = Omit<ModalVisibilityProps, "open">;--/**- * A convenience {@link IconButton} commonly needed on {@link Dialog}s, at the- * top right, to allow the user to close the dialog.- *- * Note that an explicit "Cancel" button is a better approach whenever possible,- * so use this sparingly.- */-export const DialogCloseIconButton: React.FC<DialogCloseIconButtonProps> = ({- onClose,-}) => (- <IconButton aria-label={t("close")} color="secondary" onClick={onClose}>- <CloseIcon />- </IconButton>-);diff --git a/web/apps/albums/vendor/ente-base/components/mui/FocusVisibleButton.tsx b/web/apps/albums/vendor/ente-base/components/mui/FocusVisibleButton.tsxdeleted file mode 100644index cb7e3e0636..0000000000--- a/web/apps/albums/vendor/ente-base/components/mui/FocusVisibleButton.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { Button, styled, type ButtonProps } from "@mui/material";-import React from "react";--export const RippleDisabledButton: React.FC<ButtonProps> = (props) => (- <Button disableRipple {...props} />-);--/**- * A MUI {@link Button} that shows a keyboard focus indicator (e.g. when the- * user tabs to it) and also an affordance to indicate when it is activated.- */-export const FocusVisibleButton = styled(RippleDisabledButton)(- ({ theme }) => `- &.Mui-focusVisible {- outline: 1px solid ${theme.vars.palette.stroke.base};- outline-offset: 2px;- }- &:active {- outline: 1px solid ${theme.vars.palette.stroke.faint};- outline-offset: 1px;- }-`,-);diff --git a/web/apps/albums/vendor/ente-base/components/mui/LoadingButton.tsx b/web/apps/albums/vendor/ente-base/components/mui/LoadingButton.tsxdeleted file mode 100644index 84ae32a907..0000000000--- a/web/apps/albums/vendor/ente-base/components/mui/LoadingButton.tsx+++ /dev/null@@ -1,41 +0,0 @@-import { CircularProgress, type ButtonProps } from "@mui/material";-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";-import { isSxArray } from "ente-base/components/utils/sx";-import React from "react";--/**- * A button that shows a indeterminate progress indicator if the {@link loading}- * prop is set.- *- * The button is also disabled when in the loading state.- */-export const LoadingButton: React.FC<ButtonProps & { loading?: boolean }> = ({- loading,- disabled,- color,- sx,- children,- ...rest-}) =>- loading ? (- <FocusVisibleButton- {...{ color }}- disabled- sx={[- {- "&.Mui-disabled": {- backgroundColor: `${color}.main`,- color: `${color}.contrastText`,- },- },- ...(sx ? (isSxArray(sx) ? sx : [sx]) : []),- ]}- {...rest}- >- <CircularProgress size={20} sx={{ color: "inherit" }} />- </FocusVisibleButton>- ) : (- <FocusVisibleButton {...{ color, disabled, sx }} {...rest}>- {children}- </FocusVisibleButton>- );diff --git a/web/apps/albums/vendor/ente-base/components/mui/PasswordInputAdornment.tsx b/web/apps/albums/vendor/ente-base/components/mui/PasswordInputAdornment.tsxdeleted file mode 100644index 08c4771bc6..0000000000--- a/web/apps/albums/vendor/ente-base/components/mui/PasswordInputAdornment.tsx+++ /dev/null@@ -1,49 +0,0 @@-import VisibilityIcon from "@mui/icons-material/Visibility";-import VisibilityOffIcon from "@mui/icons-material/VisibilityOff";-import { IconButton, InputAdornment } from "@mui/material";-import { t } from "i18next";-import React from "react";--interface ShowHidePasswordInputAdornmentProps {- /**- * When `true`, the password is being shown.- */- showPassword: boolean;- /**- * Called when the user wants to toggle the state of {@link showPassword}.- */- onToggle: () => void;-}--/**- * A MUI {@link InputAdornment} that can be used at the trailing edge of a- * password input field to allow the user to toggle the visibility of the- * password.- */-export const ShowHidePasswordInputAdornment: React.FC<- ShowHidePasswordInputAdornmentProps-> = ({ showPassword, onToggle: onToggle }) => {- // Prevent password field from losing focus when the input adornment is- // clicked by ignoring both the mouse up and down events. This is the- // approach mentioned in the MUI docs.- // https://mui.com/material-ui/react-text-field/#input-adornments- const preventDefault = (event: React.MouseEvent<HTMLButtonElement>) => {- event.preventDefault();- };-- return (- <InputAdornment position="end">- <IconButton- tabIndex={-1}- color="secondary"- aria-label={t("show_or_hide_password")}- onClick={onToggle}- onMouseUp={preventDefault}- onMouseDown={preventDefault}- edge="end"- >- {showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}- </IconButton>- </InputAdornment>- );-};diff --git a/web/apps/albums/vendor/ente-base/components/mui/SidebarDrawer.tsx b/web/apps/albums/vendor/ente-base/components/mui/SidebarDrawer.tsxdeleted file mode 100644index b7b0836ebe..0000000000--- a/web/apps/albums/vendor/ente-base/components/mui/SidebarDrawer.tsx+++ /dev/null@@ -1,123 +0,0 @@-import ArrowBackIcon from "@mui/icons-material/ArrowBack";-import CloseIcon from "@mui/icons-material/Close";-import {- Box,- Drawer,- IconButton,- Stack,- Typography,- type DrawerProps,-} from "@mui/material";-import type { ModalVisibilityProps } from "ente-base/components/utils/modal";-import React from "react";--export const SidebarDrawer: React.FC<DrawerProps> = ({- slotProps,- children,- ...rest-}) => (- <Drawer- {...rest}- slotProps={{- ...(slotProps ?? {}),- paper: {- sx: {- maxWidth: "375px",- width: "100%",- scrollbarWidth: "thin",- "&&": { padding: 0 },- },- },- }}- >- <Box sx={{ p: 1 }}>{children}</Box>- </Drawer>-);--export type NestedSidebarDrawerVisibilityProps = ModalVisibilityProps & {- onRootClose: () => void;-};--export const NestedSidebarDrawer: React.FC<- NestedSidebarDrawerVisibilityProps & DrawerProps-> = ({ onClose, onRootClose, ...rest }) => {- const handleClose: DrawerProps["onClose"] = (_, reason) => {- if (reason == "backdropClick") {- onClose();- onRootClose();- } else {- onClose();- }- };-- return (- <SidebarDrawer- transitionDuration={0}- slotProps={{- backdrop: { sx: { "&&&": { backgroundColor: "transparent" } } },- }}- onClose={handleClose}- {...rest}- />- );-};--type SidebarDrawerTitlebarProps = Pick<- NestedSidebarDrawerVisibilityProps,- "onClose" | "onRootClose"-> & {- title: string;- caption?: string;- actionButton?: React.ReactNode;-};--export const SidebarDrawerTitlebar: React.FC<SidebarDrawerTitlebarProps> = ({- title,- caption,- onClose,- onRootClose,- actionButton,-}) => (- <Stack sx={{ gap: "4px" }}>- <Stack direction="row" sx={{ justifyContent: "space-between" }}>- <IconButton onClick={onClose} color="primary">- <ArrowBackIcon />- </IconButton>- <Stack direction="row" sx={{ gap: "4px" }}>- {actionButton && actionButton}- <IconButton onClick={onRootClose} color="secondary">- <CloseIcon />- </IconButton>- </Stack>- </Stack>- <Stack sx={{ px: "16px", gap: "4px" }}>- <Typography variant="h3">{title}</Typography>- <Typography- variant="small"- sx={{- color: "text.muted",- wordBreak: "break-all",- px: "1px",- minHeight: "17px",- }}- >- {caption}- </Typography>- </Stack>- </Stack>-);--export const TitledNestedSidebarDrawer: React.FC<- React.PropsWithChildren<- NestedSidebarDrawerVisibilityProps &- Pick<DrawerProps, "anchor"> &- SidebarDrawerTitlebarProps- >-> = ({ open, onClose, onRootClose, anchor, children, ...rest }) => (- <NestedSidebarDrawer {...{ open, onClose, onRootClose, anchor }}>- <Stack sx={{ gap: "4px", py: "12px" }}>- <SidebarDrawerTitlebar {...{ onClose, onRootClose }} {...rest} />- {children}- </Stack>- </NestedSidebarDrawer>-);diff --git a/web/apps/albums/vendor/ente-base/components/mui/index.tsx b/web/apps/albums/vendor/ente-base/components/mui/index.tsxdeleted file mode 100644index a440a90964..0000000000--- a/web/apps/albums/vendor/ente-base/components/mui/index.tsx+++ /dev/null@@ -1,15 +0,0 @@-import { IconButton, styled } from "@mui/material";--/**- * Convenience typed props for a component that acts like a push button.- */-export interface ButtonishProps {- onClick: () => void;-}--/**- * A MUI {@link IconButton} filled in with a faint background.- */-export const FilledIconButton = styled(IconButton)(({ theme }) => ({- backgroundColor: theme.vars.palette.fill.faint,-}));diff --git a/web/apps/albums/vendor/ente-base/components/pages/404.tsx b/web/apps/albums/vendor/ente-base/components/pages/404.tsxdeleted file mode 100644index 3940190c92..0000000000--- a/web/apps/albums/vendor/ente-base/components/pages/404.tsx+++ /dev/null@@ -1,32 +0,0 @@-import { useRouter } from "next/router";-import React, { useEffect } from "react";--/**- * A reusable 404 page.- */-const Page: React.FC = () => {- // [Note: 404 back to home]- //- // In the desktop app, if the user presses the refresh button when the URL- // has an attached query parameter, e.g. "/gallery?collectionId=xxx", then- // the code in next-electron-server blindly appends the html extension to- // this URL, resulting in it trying to open "gallery?collectionId=xxx.html"- // instead of "gallery.html". It doesn't find such a file, causing it open- // "404.html" (the static file generated from this file).- //- // One way around is to patch the package, e.g.- // https://github.com/ente-io/next-electron-server/pull/1/files- //- // However, redirecting back to the root is arguably a better fallback in- // all cases (even when running on our website), since our app is a SPA.-- const router = useRouter();-- useEffect(() => {- void router.push("/");- }, [router]);-- return <></>;-};--export default Page;diff --git a/web/apps/albums/vendor/ente-base/components/utils/dialog.tsx b/web/apps/albums/vendor/ente-base/components/utils/dialog.tsxdeleted file mode 100644index 04cdc48711..0000000000--- a/web/apps/albums/vendor/ente-base/components/utils/dialog.tsx+++ /dev/null@@ -1,67 +0,0 @@-import ErrorOutlineIcon from "@mui/icons-material/ErrorOutline";-import { t } from "i18next";-import { useCallback, useState } from "react";-import type { MiniDialogAttributes } from "../MiniDialog";--/**- * A React hook for simplifying the provisioning of a {@link showMiniDialog}- * function to inject in app contexts, and of the other props that are needed to- * be passed to the {@link AttributedMiniDialog}.- */-export const useAttributedMiniDialog = () => {- const [attributes, setAttributes] = useState<- MiniDialogAttributes | undefined- >(undefined);-- const [open, setOpen] = useState(false);-- const showMiniDialog = useCallback(- (newAttributes: MiniDialogAttributes) => {- setAttributes((attributes) =>- attributes?.nonReplaceable ? attributes : newAttributes,- );- setOpen(true);- },- [],- );-- const handleClose = useCallback(() => setOpen(false), []);-- return {- showMiniDialog,- miniDialogProps: { open, onClose: handleClose, attributes },- };-};--/**- * A convenience function to construct {@link MiniDialogAttributes} for showing- * error dialogs.- *- * It takes one or two arguments.- *- * - If both are provided, then the first one is taken as the title and the- * second one as the message.- *- * - Otherwise it sets a default title and use the only argument as the message.- */-export const errorDialogAttributes = (- messageOrTitle: string,- optionalMessage?: string,-): MiniDialogAttributes => {- const title = optionalMessage ? messageOrTitle : t("error");- const message = optionalMessage ?? messageOrTitle;-- return {- title,- icon: <ErrorOutlineIcon />,- message,- continue: { color: "critical" },- cancel: false,- };-};--export const genericErrorDialogAttributes = () =>- errorDialogAttributes(t("generic_error"));--export const genericRetriableErrorDialogAttributes = () =>- errorDialogAttributes(t("generic_error_retry"));diff --git a/web/apps/albums/vendor/ente-base/components/utils/hooks-app.ts b/web/apps/albums/vendor/ente-base/components/utils/hooks-app.tsdeleted file mode 100644index 89a3033ef3..0000000000--- a/web/apps/albums/vendor/ente-base/components/utils/hooks-app.ts+++ /dev/null@@ -1,21 +0,0 @@-import { setupI18n } from "ente-base/i18n";-import { useEffect, useState } from "react";--/**- * A hook that initializes the localization library that we use.- *- * This is only meant to be called from the top level `_app.tsx`, as this- * initialization is intended to happen only once for the lifetime of the app.- *- * @returns a boolean which will be set to true when the localized strings have- * been loaded.- */-export const useSetupI18n = () => {- const [isI18nReady, setIsI18nReady] = useState(false);-- useEffect(() => {- void setupI18n().finally(() => setIsI18nReady(true));- }, []);-- return isI18nReady;-};diff --git a/web/apps/albums/vendor/ente-base/components/utils/hooks.ts b/web/apps/albums/vendor/ente-base/components/utils/hooks.tsdeleted file mode 100644index f89e7abc1d..0000000000--- a/web/apps/albums/vendor/ente-base/components/utils/hooks.ts+++ /dev/null@@ -1,79 +0,0 @@-import { useMediaQuery, useTheme } from "@mui/material";-import { useCallback, useEffect, useRef, useState } from "react";--/**- * Return true if the screen width is classified as a small size. This is often- * treated as an (rather arbitrary) cutoff for "mobile" sized screens.- *- * We use the MUI "sm" (small, 600px) breakpoint as the cutoff. This hook will- * return true if the size of the window's width is less than 600px.- */-export const useIsSmallWidth = () =>- useMediaQuery(useTheme().breakpoints.down("sm"));--/**- * Heuristic "isMobileOrTablet"-ish check using a pointer media query.- *- * The absence of fine-resolution pointing device can be taken a quick and proxy- * for detecting if the user is using a mobile or tablet.- *- * This is of course not going to work in all scenarios (e.g. someone connecting- * their mice to their tablet), but ad-hoc user agent checks are not problem- * free either. This media query should be accurate enough for cases where false- * positives will degrade gracefully.- *- * See: https://github.com/mui/mui-x/issues/10039- */-export const useIsTouchscreen = () =>- useMediaQuery("(hover: none) and (pointer: coarse)", { noSsr: true });--/**- * A hook that manages a transient "copied" state.- *- * @param text The text to copy.- *- * @returns a tuple containing a boolean {@link copied} indicating if a copy has- * just successfully happened, and a function {@link onCopy} to trigger the- * copy.- */-export const useClipboardCopy = (- text: string,-): [copied: boolean, onCopy: () => void] => {- const [copied, setCopied] = useState(false);-- const handleCopyLink = useCallback(() => {- void navigator.clipboard.writeText(text).then(() => {- setCopied(true);- setTimeout(() => setCopied(false), 1000);- });- }, [text]);-- return [copied, handleCopyLink];-};--/**- * A hook that runs a callback at a specified interval.- *- * @param callback The function to call on each interval tick.- * @param delay The interval in milliseconds, or null to pause the interval.- */-export const useInterval = (- callback: () => void,- delay: number | null,-): void => {- const savedCallback = useRef(callback);-- // Remember the latest callback- useEffect(() => {- savedCallback.current = callback;- }, [callback]);-- // Set up the interval- useEffect(() => {- if (delay === null) return;-- const tick = () => savedCallback.current();- const id = setInterval(tick, delay);- return () => clearInterval(id);- }, [delay]);-};diff --git a/web/apps/albums/vendor/ente-base/components/utils/modal.ts b/web/apps/albums/vendor/ente-base/components/utils/modal.tsdeleted file mode 100644index 0b40c9d786..0000000000--- a/web/apps/albums/vendor/ente-base/components/utils/modal.ts+++ /dev/null@@ -1,28 +0,0 @@-import { useCallback, useState } from "react";--/**- * Common props that control the display of a modal (e.g. dialog, drawer)- * component.- */-export interface ModalVisibilityProps {- /** If `true`, the component is shown. */- open: boolean;- /** Callback fired when the component requests to be closed. */- onClose: () => void;-}--/**- * A convenience hook for keeping the state for opening and closing a modal, and- * exposing a function to close the modal whose identity is stable.- *- * These props can be passed verbatim to our components that expect- * {@link ModalVisibilityProps}.- */-export const useModalVisibility = () => {- const [open, setOpen] = useState(false);-- const show = useCallback(() => setOpen(true), []);- const onClose = useCallback(() => setOpen(false), []);-- return { show, props: { open, onClose } };-};diff --git a/web/apps/albums/vendor/ente-base/components/utils/mui-theme.d.ts b/web/apps/albums/vendor/ente-base/components/utils/mui-theme.d.tsdeleted file mode 100644index 1cdcdef9e2..0000000000--- a/web/apps/albums/vendor/ente-base/components/utils/mui-theme.d.ts+++ /dev/null@@ -1,266 +0,0 @@-import type { PaletteColor } from "@mui/material";-import React from "react";--// Import the module augmentation that provides types for `theme.vars.*`.-import type {} from "@mui/material/themeCssVarsAugmentation";--// Add new tokens to the Palette.-//-// https://mui.com/material-ui/customization/css-theme-variables/usage/#adding-new-theme-tokens--declare module "@mui/material/styles" {- /**- * Add new "background" color tokens, giving us:- *- * - background.default- * - background.paper- * - background.paper2- * - background.elevatedPaper- * - background.searchInput- */- interface TypeBackground {- /**- * A second level elevation, indicating a paper within a paper.- */- paper2: string;- /**- * The first among background.paper and background.paper2 that is not- * the same as the default background.- *- * In light mode, background.default and background.paper are the same,- * while in dark mode background.paper is already elevated. This- * property can be used to obtain the first paper that is actually- * elevated above the background irrespective of the theme.- */- elevatedPaper: string;- /**- * Background color for the search input area.- */- searchInput: string;- }-- /**- * Define a new set of tokens for the "text" color in the palette which- * matches the strength triads we use for stroke and fill.- *- * Since there is no way to override or replace the existing tokens, we can- * only augment the interface with our new tokens. However, our code should- * NOT use the default tokens provided by MUI:- *- * - text.primary <- Don't use- * - text.secondary <- Don't use- * - text.disabled <- Don't use- *- * Instead, use these three:- *- * - text.base- * - text.muted- * - text.faint- */- interface TypeText {- base: string;- muted: string;- faint: string;- }-- interface Palette {- /**- * The main brand color. e.g. the "Ente green", the "Auth purple".- *- * This does not vary with the color scheme.- */- accent: PaletteColor;- /**- * The color for potentially dangerous actions, errors, or other things- * we would like to call the user's attention out to.- *- * MUI has an "error" palette color, but that seems to semantically not- * gel with all uses. e.g. it feels weird to create a button with- * color="error".- *- * This does not vary with the color scheme.- */- critical: PaletteColor;- /**- * Neutral transparent colors for the stroke of icons and other outlines.- *- * These change with the color scheme.- *- * They come in three strengths which are meant to play nicely with the- * corresponding strengths of "text.*" and "fill.*", and an extra- * "fainter" variant for ad-hoc uses.- */- stroke: { base: string; muted: string; faint: string; fainter: string };- /**- * Neutral transparent colors for filling small areas like icon or- * button backgrounds.- *- * These change with the color scheme.- *- * They come in three strengths which are meant to play nicely with the- * corresponding strengths of "text.*" and "stroke.*", plus extra ones.- *- * Some strengths also have a hover variant, useful to indicate hover on- * buttons and menu items that use the corresponding fill.- */- fill: {- base: string;- muted: string;- faint: string;- faintHover: string;- fainter: string;- };- /**- * Transparent background fills that serve as the backdrop of modals,- * dialogs and drawers etc.- *- * These change with the color scheme.- */- backdrop: { base: string; muted: string; faint: string };- /**- * Various ad-hoc fixed colors used by our designs.- *- * These do not change with the color scheme.- *- * Some places in the code also use the grey PaletteColor provided by- * MUI whose corresponding color values can be seen at- * https://mui.com/material-ui/customization/default-theme/- */- fixed: {- /**- * The color of a switch when it is enabled.- */- switchOn: string;- /**- * A subset of the dark mode colors, fixed so that they don't change- * even when the app is in light mode.- */- dark: {- background: Omit<TypeBackground, "elevatedPaper">;- text: Omit<TypeText, "primary" | "secondary" | "disabled">;- divider: string;- };- };- /**- * MUI as of v6 does not allow customizing shadows easily. This is due- * for change: https://github.com/mui/material-ui/issues/44291.- *- * Meanwhile use a custom variable. Since it is specific to the color- * scheme, keep it inside the palette.- */- boxShadow: {- /**- * Drop shadow for the MUI {@link Paper}. In particular, this also- * gets used as the drop shadow for {@link Dialog} (which uses a- * {@link Paper} to embed its contents).- */- paper: string;- /**- * Drop shadow for the MUI {@link Menu} and other small floating- * elements like the {@link Notification} {@link Snackbar}.- */- menu: string;- /** Currently unused. */- button: string;- };- }-- interface PaletteOptions {- accent?: Palette["accent"];- critical?: Palette["critical"];- stroke?: Palette["stroke"];- fill?: Palette["fill"];- backdrop?: Palette["backdrop"];- fixed?: Palette["fixed"];- boxShadow?: Palette["boxShadow"];- }-}--// Make our custom palette colors available for use as the color prop of various-// MUI components.--declare module "@mui/material/Button" {- interface ButtonPropsColorOverrides {- // Turn off MUI provided palette colors we don't use.- error: false;- success: false;- info: false;- warning: false;- // Add our custom palette colors.- accent: true;- critical: true;- }-}--declare module "@mui/material/IconButton" {- interface IconButtonPropsColorOverrides {- // Turn off MUI provided palette colors we don't use.- error: false;- success: false;- info: false;- warning: false;- }-}--declare module "@mui/material/Checkbox" {- interface CheckboxPropsColorOverrides {- accent: true;- }-}--declare module "@mui/material/Switch" {- interface SwitchPropsColorOverrides {- accent: true;- }-}--declare module "@mui/material/SvgIcon" {- interface SvgIconPropsColorOverrides {- accent: true;- }-}--declare module "@mui/material/CircularProgress" {- interface CircularProgressPropsColorOverrides {- accent: true;- }-}--// Tell TypeScript about our Typography variants-//-// https://mui.com/material-ui/customization/typography/#adding-amp-disabling-variants--declare module "@mui/material/styles" {- interface TypographyVariants {- body: React.CSSProperties;- small: React.CSSProperties;- mini: React.CSSProperties;- tiny: React.CSSProperties;- }-- interface TypographyVariantsOptions {- body?: React.CSSProperties;- small?: React.CSSProperties;- mini?: React.CSSProperties;- tiny?: React.CSSProperties;- }-}--declare module "@mui/material/Typography" {- // Update the Typography's variant prop options.- interface TypographyPropsVariantOverrides {- // Turn off MUI provided variants we don't use.- subtitle1: false;- subtitle2: false;- body1: false;- body2: false;- caption: false;- button: false;- overline: false;- // Add our custom variants.- body: true;- small: true;- mini: true;- tiny: true;- }-}diff --git a/web/apps/albums/vendor/ente-base/components/utils/sx.ts b/web/apps/albums/vendor/ente-base/components/utils/sx.tsdeleted file mode 100644index e3f0cf301e..0000000000--- a/web/apps/albums/vendor/ente-base/components/utils/sx.ts+++ /dev/null@@ -1,25 +0,0 @@-import { type SxProps, type Theme } from "@mui/material";-import { type SystemStyleObject } from "@mui/system";--/**- * Wrapper over Array.isArray that retains the TypeScript type for SxProps when- * trying to spread them.- *- * The recommended pattern to use sx props in our own component (whilst- * forwarding them to the underlying MUI component) is to:- *- * ...(Array.isArray(sx) ? sx : [sx])- *- * However, currently (as of MUI v6), this runs afoul of the- * 'no-unsafe-assignment' eslint rule. This function provides a workaround, and- * can be used as a drop-in replacement of Array.isArray in the above pattern.- *- * Ref: https://github.com/mui/material-ui/issues/37730- */-export const isSxArray = (- sx: SxProps<Theme>,-): sx is readonly (- | boolean- | SystemStyleObject<Theme>- | ((theme: Theme) => SystemStyleObject<Theme>)-)[] => Array.isArray(sx);diff --git a/web/apps/albums/vendor/ente-base/components/utils/theme.ts b/web/apps/albums/vendor/ente-base/components/utils/theme.tsdeleted file mode 100644index 6e8e620da0..0000000000--- a/web/apps/albums/vendor/ente-base/components/utils/theme.ts+++ /dev/null@@ -1,1108 +0,0 @@-import type { Theme, TypographyVariantsOptions } from "@mui/material";-import { createTheme } from "@mui/material";-import type { Components } from "@mui/material/styles";-import type { AppName } from "ente-base/app";--const getTheme = (appName: AppName): Theme => {- const colors = getColors(appName);- const cs = getColorSchemes(colors);- // Cast app should always be shown in dark.- const colorSchemes =- appName == "cast" ? { ...cs, light: cs.dark } : { ...cs };- return createTheme({- cssVariables: { colorSchemeSelector: "class" },- colorSchemes,- typography: getTypography(appName),- components: getComponents(appName),- shape: {- // Increase the default border radius multiplier from 4 to 8.- borderRadius: 8,- },- transitions: {- // Increase the default transition out duration from 195 to 300.- duration: { leavingScreen: 300 },- },- });-};--/**- * [Note: Colors]- *- * The word "color" in MUI stands for different things. In particular, the color- * prop for (e.g.) a Button is not the same as the color passed in the sx prop.- *- * There are three layers (only the first is necessary, rest are semantic):- *- * 1. Consider some color, say a shade of red. This will be represented by its- * exact CSS color value, say "#ee0000".- *- * 2. These can be groups of color values that have roughly the same hue, but- * different levels of saturation. Such hue groups are arranged together into- * a "Colors" exported by "@mui/material":- *- * export interface Color {- * 50: string;- * 100: string;- * ...- * 800: string;- * 900: string;- * A100: string;- * ...- * A700: string;- * }- *- * 3. Finally, there are "PaletteColors" (the naming of props, and- * documentation within MUI (as of v6), omits the palette qualifier).- *- * export interface PaletteColor {- * light: string;- * main: string;- * dark: string;- * contrastText: string;- * }- *- * The PaletteColors are what we use in the MUI component props (e.g. Button).- * The PaletteColors are defined by providing color values for the four "tokens"- * that make them up, either directly ("#aa000") or via Colors ("red[500]").- *- * Within the sx prop we need to specify a color value, which can come from the- * palette. The "palette", as defined by the palette property we provide when- * creating the theme, can consist of arbitrary (and nestable) key value pairs.- *- * Within sx prop, the "color" and "backgroundColor" props can refer to paths- * inside this palette object. That is,- *- * sx={{ color: "foo.bar" }}- *- * resolves to theme.vars.palette.foo.bar.- *- * [Note: Color names]- *- * When defining color names, there is some attempt at trying to use MUI v6,- * which uses MD (Material Design) v2, nomenclature when feasible (just to keep- * the number of concepts low), but as such, our color names should not be- * thought of as following Material Design, and should be treated as arbitrary- * tokens reflecting our own design system.- *- * Some callouts:- *- * - Our "primary" and "secondary" are neutral grays instead of the two-tone- * primary and secondary in MD. Our "accent" is corresponds to the MD primary.- *- * - Our "critical" is similar to and the alternative for the MD error (which is- * not used).- *- * - Two of the other default MD PaletteColors - warning, success - are used- * rarely, while info is not used at all.- *- * [Note: Theme and palette custom variables]- *- * Custom variables can be added to both the top level theme object, and to the- * palette object within the theme. One would imagine that within the palette- * there would only be colors that follow PaletteColor, but that's not something- * MUI itself follows.- *- * So there is no particular reason to place custom color related variables in- * theme vs in the palette. As a convention:- *- * - Custom colors (even if they're not PaletteColors) go within the palette.- *- * - Non-color tokens that depend on the color scheme (e.g. box shadows) also go- * within the palette so that they can be made color scheme specific.- *- * - All other custom variables remain within the top level theme.- */-const getColors = (appName: AppName) => ({- ..._colors,- ...{- fixed: {- ..._colors.fixed,- dark: {- background: _colors.dark.background,- text: _colors.dark.text,- divider: _colors.dark.stroke.faint,- },- },- },- ...{- accent:- appName == "auth"- ? _colors.accentAuth- : appName == "share" || appName == "locker"- ? _colors.accentShare- : appName == "ensu"- ? _colors.accentEnsu- : _colors.accentPhotos,- accentDark:- appName == "ensu"- ? _colors.accentEnsuDark- : appName == "auth"- ? _colors.accentAuth- : appName == "share" || appName == "locker"- ? _colors.accentShare- : _colors.accentPhotos,- },- ...{- accentContrastText:- appName == "ensu" ? _colors.fixed.black : _colors.fixed.white,- },- ...{- light:- appName == "share" || appName == "locker"- ? _colors.lightShare- : appName == "ensu"- ? _colors.lightEnsu- : _colors.light,- },- ...{- dark:- appName == "share" || appName == "locker"- ? _colors.darkShare- : appName == "ensu"- ? _colors.darkEnsu- : _colors.dark,- },-});--/**- * The color values.- *- * Use this arbitrarily shaped object to define the palette. This avoid- * duplication across color schemes, and also helps see if there are any- * reusable colors.- */-const _colors = {- accentPhotos: { dark: "#00b33c", main: "#1db954", light: "#01de4d" },- accentAuth: { dark: "#8e0fcb", main: "#9610d6", light: "#8e2de2" },- accentShare: { dark: "#0056CC", main: "#1071FF", light: "#1071FF" },- accentEnsu: { dark: "#f5d93a", main: "#f5d93a", light: "#f5d93a" },- accentEnsuDark: { dark: "#f5d93a", main: "#f5d93a", light: "#f5d93a" },- fixed: {- white: "#fff",- black: "#000",- success: "#1db954",- golden: "#ffc107",- danger: { dark: "#f53434", main: "#ea3f3f", light: "#ff6565" },- switchOn: "#2eca45",- },- lightShare: {- background: {- default: "#FAFAFA",- paper: "#fff",- paper2: "#fbfbfb",- searchInput: "#f3f3f3",- },- backdrop: {- base: "rgba(255 255 255 / 0.92)",- muted: "rgba(255 255 255 / 0.75)",- faint: "rgba(255 255 255 / 0.30)",- },- text: {- base: "#000",- muted: "rgba(0 0 0 / 0.60)",- faint: "rgba(0 0 0 / 0.50)",- },- fill: {- base: "#000",- muted: "rgba(0 0 0 / 0.12)",- faint: "rgba(0 0 0 / 0.04)",- faintHover: "rgba(0 0 0 / 0.08)",- fainter: "rgba(0 0 0 / 0.02)",- },- secondary: { main: "#f5f5f5", hover: "#e9e9e9" },- stroke: {- base: "#000",- muted: "rgba(0 0 0 / 0.24)",- faint: "rgba(0 0 0 / 0.12)",- fainter: "rgba(0 0 0 / 0.06)",- },- boxShadow: {- paper: "0px 0px 10px rgba(0 0 0 / 0.25)",- menu: "0px 0px 6px rgba(0 0 0 / 0.16), 0px 3px 6px rgba(0 0 0 / 0.12)",- button: "0px 4px 4px rgba(0 0 0 / 0.25)",- },- },- lightEnsu: {- background: {- default: "#F8F5F0",- paper: "#F8F5F0",- paper2: "#FFFDF8",- searchInput: "#F0EBE4",- },- backdrop: {- base: "rgba(248 245 240 / 0.92)",- muted: "rgba(248 245 240 / 0.75)",- faint: "rgba(248 245 240 / 0.30)",- },- text: {- base: "#1A1A1A",- muted: "#8A8680",- faint: "rgba(138 134 128 / 0.50)",- },- fill: {- base: "#1A1A1A",- muted: "rgba(26 26 26 / 0.12)",- faint: "#F0EBE4",- faintHover: "#E7E1D8",- fainter: "#F8F5F0",- },- secondary: { main: "#F0EBE4", hover: "#E7E1D8" },- stroke: {- base: "#1A1A1A",- muted: "rgba(26 26 26 / 0.24)",- faint: "#D4D0C8",- fainter: "rgba(26 26 26 / 0.06)",- },- boxShadow: {- paper: "0px 0px 10px rgba(0 0 0 / 0.18)",- menu: "0px 0px 6px rgba(0 0 0 / 0.14), 0px 3px 6px rgba(0 0 0 / 0.10)",- button: "0px 4px 4px rgba(0 0 0 / 0.18)",- },- },- darkShare: {- background: {- default: "#161616",- paper: "#212121",- paper2: "#252525",- searchInput: "#212121",- },- backdrop: {- base: "rgba(0 0 0 / 0.90)",- muted: "rgba(0 0 0 / 0.65)",- faint: "rgba(0 0 0 / 0.20)",- },- text: {- base: "#fff",- muted: "rgba(255 255 255 / 0.70)",- faint: "rgba(255 255 255 / 0.50)",- },- fill: {- base: "#fff",- muted: "rgba(255 255 255 / 0.16)",- faint: "rgba(255 255 255 / 0.12)",- faintHover: "rgba(255 255 255 / 0.16)",- fainter: "rgba(255 255 255 / 0.05)",- },- secondary: { main: "#2b2b2b", hover: "#373737" },- stroke: {- base: "#fff",- muted: "rgba(255 255 255 / 0.24)",- faint: "rgba(255 255 255 / 0.16)",- fainter: "rgba(255 255 255 / 0.12)",- },- boxShadow: {- paper: "0px 2px 12px rgba(0 0 0 / 0.75)",- menu: "0px 0px 6px rgba(0 0 0 / 0.50), 0px 3px 6px rgba(0 0 0 / 0.25)",- button: "0px 4px 4px rgba(0 0 0 / 0.75)",- },- },- darkEnsu: {- background: {- default: "#141414",- paper: "#1E1E1E",- paper2: "#1E1E1E",- searchInput: "#1E1E1E",- },- backdrop: {- base: "rgba(20 20 20 / 0.90)",- muted: "rgba(20 20 20 / 0.65)",- faint: "rgba(20 20 20 / 0.20)",- },- text: {- base: "#E8E4DF",- muted: "#777777",- faint: "rgba(119 119 119 / 0.50)",- },- fill: {- base: "#E8E4DF",- muted: "rgba(232 228 223 / 0.16)",- faint: "#1E1E1E",- faintHover: "#2A2A2A",- fainter: "#141414",- },- secondary: { main: "#1E1E1E", hover: "#2A2A2A" },- stroke: {- base: "#E8E4DF",- muted: "rgba(232 228 223 / 0.24)",- faint: "#2A2A2A",- fainter: "rgba(232 228 223 / 0.12)",- },- boxShadow: {- paper: "0px 2px 12px rgba(0 0 0 / 0.75)",- menu: "0px 0px 6px rgba(0 0 0 / 0.50), 0px 3px 6px rgba(0 0 0 / 0.25)",- button: "0px 4px 4px rgba(0 0 0 / 0.75)",- },- },- light: {- // Keep these solid.- background: {- default: "#fff",- paper: "#fff",- paper2: "#fbfbfb",- searchInput: "#f3f3f3",- },- backdrop: {- base: "rgba(255 255 255 / 0.92)",- muted: "rgba(255 255 255 / 0.75)",- faint: "rgba(255 255 255 / 0.30)",- },- text: {- base: "#000",- muted: "rgba(0 0 0 / 0.60)",- faint: "rgba(0 0 0 / 0.50)",- },- fill: {- base: "#000",- muted: "rgba(0 0 0 / 0.12)",- faint: "rgba(0 0 0 / 0.04)",- faintHover: "rgba(0 0 0 / 0.08)",- fainter: "rgba(0 0 0 / 0.02)",- },- // MUI (as of v6.4) doesn't like it if we specify a non-solid color for- // primary.main or secondary.main, or don't specify it using the #nnnnnn- // notation; it seems to mess with the derivation of the color channels.- secondary: { main: "#f5f5f5", hover: "#e9e9e9" },- stroke: {- base: "#000",- muted: "rgba(0 0 0 / 0.24)",- faint: "rgba(0 0 0 / 0.12)",- fainter: "rgba(0 0 0 / 0.06)",- },- boxShadow: {- paper: "0px 0px 10px rgba(0 0 0 / 0.25)",- menu: "0px 0px 6px rgba(0 0 0 / 0.16), 0px 3px 6px rgba(0 0 0 / 0.12)",- button: "0px 4px 4px rgba(0 0 0 / 0.25)",- },- },- dark: {- background: {- default: "#000",- paper: "#1b1b1b",- paper2: "#252525",- searchInput: "#1b1b1b",- },- backdrop: {- base: "rgba(0 0 0 / 0.90)",- muted: "rgba(0 0 0 / 0.65)",- faint: "rgba(0 0 0 / 0.20)",- },- text: {- base: "#fff",- muted: "rgba(255 255 255 / 0.70)",- faint: "rgba(255 255 255 / 0.50)",- },- fill: {- base: "#fff",- muted: "rgba(255 255 255 / 0.16)",- faint: "rgba(255 255 255 / 0.12)",- faintHover: "rgba(255 255 255 / 0.16)",- fainter: "rgba(255 255 255 / 0.05)",- },- secondary: { main: "#2b2b2b", hover: "#373737" },- stroke: {- base: "#fff",- muted: "rgba(255 255 255 / 0.24)",- faint: "rgba(255 255 255 / 0.16)",- fainter: "rgba(255 255 255 / 0.12)",- },- boxShadow: {- paper: "0px 2px 12px rgba(0 0 0 / 0.75)",- menu: "0px 0px 6px rgba(0 0 0 / 0.50), 0px 3px 6px rgba(0 0 0 / 0.25)",- button: "0px 4px 4px rgba(0 0 0 / 0.75)",- },- },-};--const getColorSchemes = (colors: ReturnType<typeof getColors>) => ({- light: {- palette: {- background: {- ...colors.light.background,- elevatedPaper: colors.light.background.paper2,- },- backdrop: colors.light.backdrop,- primary: {- main: colors.fixed.black,- contrastText: colors.fixed.white,- },- secondary: {- main: colors.light.secondary.main,- dark: colors.light.secondary.hover,- contrastText: colors.light.text.base,- },- success: { main: colors.fixed.success },- warning: { main: colors.fixed.golden },- accent: {- main: colors.accent.main,- dark: colors.accent.dark,- light: colors.accent.light,- contrastText: colors.accentContrastText,- },- critical: {- main: colors.fixed.danger.main,- dark: colors.fixed.danger.dark,- light: colors.fixed.danger.light,- contrastText: colors.fixed.white,- },- text: {- // Alias the tokens used by MUI to the ones that we use. This way,- // we don't need to change the default ("primary"), or update the- // MUI internal styling that refers to these tokens.- //- // Our own code should not use these.- primary: colors.light.text.base,- secondary: colors.light.text.muted,- disabled: colors.light.text.faint,- // Our color tokens.- base: colors.light.text.base,- muted: colors.light.text.muted,- faint: colors.light.text.faint,- },- fill: colors.light.fill,- stroke: colors.light.stroke,- divider: colors.light.stroke.faint,- fixed: colors.fixed,- boxShadow: colors.light.boxShadow,- // Override some MUI defaults for styling action elements like- // buttons and menu items.- //- // Nb: There are more where these came from, currently those don't- // affect us, but in the future they might.- //- // https://github.com/mui/material-ui/blob/v6.4.0/packages/mui-material/src/styles/createPalette.js#L68- action: {- // The color of an active action like an icon button.- active: colors.light.stroke.base,- // The color of an hovered action.- hover: colors.light.fill.faintHover,- // For an icon button, the hover background color is derived- // from the active color above and this opacity. Use a value- // that results in the same result as faintHover.- hoverOpacity: 0.08,- // The color of a disabled action.- disabled: colors.light.text.faint,- // The background color of a disabled action.- disabledBackground: colors.light.fill.faint,- },- // Override some internal MUI defaults that impact the components- // which we use.- //- // https://github.com/mui/material-ui/blob/v6.4.0/packages/mui-material/src/styles/createThemeWithVars.js#L271- FilledInput: {- bg: colors.light.fill.faint,- hoverBg: colors.light.fill.faintHover,- // While we don't specifically have disabled inputs, TextInputs- // do get disabled when the form is submitting, and this value- // comes into play then.- disabledBg: colors.light.fill.fainter,- },- },- },- // -- See the light mode section for comments- dark: {- palette: {- background: {- ...colors.dark.background,- elevatedPaper: colors.dark.background.paper,- },- backdrop: colors.dark.backdrop,- primary: {- main: colors.fixed.white,- contrastText: colors.fixed.black,- },- secondary: {- main: colors.dark.secondary.main,- dark: colors.dark.secondary.hover,- contrastText: colors.dark.text.base,- },- success: { main: colors.fixed.success },- warning: { main: colors.fixed.golden },- accent: {- main: colors.accentDark.main,- dark: colors.accentDark.dark,- light: colors.accentDark.light,- contrastText: colors.accentContrastText,- },- critical: {- main: colors.fixed.danger.main,- dark: colors.fixed.danger.dark,- light: colors.fixed.danger.light,- contrastText: colors.fixed.white,- },- text: {- primary: colors.dark.text.base,- secondary: colors.dark.text.muted,- disabled: colors.dark.text.faint,- base: colors.dark.text.base,- muted: colors.dark.text.muted,- faint: colors.dark.text.faint,- },- fill: colors.dark.fill,- stroke: colors.dark.stroke,- divider: colors.dark.stroke.faint,- fixed: colors.fixed,- boxShadow: colors.dark.boxShadow,- // -- See the light mode section for comments- action: {- active: colors.dark.stroke.base,- hover: colors.dark.fill.faintHover,- hoverOpacity: 0.16,- disabled: colors.dark.text.faint,- disabledBackground: colors.dark.fill.faint,- },- FilledInput: {- bg: colors.dark.fill.faint,- hoverBg: colors.dark.fill.faintHover,- disabledBg: colors.dark.fill.fainter,- },- },- },-});--/**- * [Note: Font weights]- *- * We only use three font weights:- *- * - 500 (sx "regular")- * - 600 (sx "medium")- * - 700 (sx "bold", CSS "bold")- *- * While the sx prop allows us to use keywords "regular", "medium" and "bold",- * which we do elsewhere in the code, within this file those keywords cannot be- * used in all contexts because they instead map to the CSS keywords. To avoid- * any confusion, within this file we only use the numeric values.- *- * ---- *- * MUI (as of v6) uses the following font weights by default:- *- * - fontWeightLight 300- * - fontWeightRegular 400- * - fontWeightMedium 500- * - fontWeightBold 700- *- * The browser default (CSS keyword "normal"), is also 400.- *- * However for Inter, the font that we use, 400 is too light, and to improve- * legibility we change fontWeightRegular to 500.- *- * Correspondingly, we shift fontWeightMedium to 600. fontWeightBold then ends- * up mapping back to 700, which also nicely coincides with the CSS keyword- * "bold".- *- * MUI uses fontWeightLight only as the default font weight for the h1 and h2- * variants, but we override their font weight in our theme. Thus we don't need- * to bother with the light variant (though for consistency of specifying every- * value, we alias it the same weight as regular, 500).- */-const baseTypography: TypographyVariantsOptions = {- fontFamily: '"Inter Variable", sans-serif',- fontWeightLight: 500,- fontWeightRegular: 500 /* CSS baseline reset sets this as the default */,- fontWeightMedium: 600,- fontWeightBold: 700,- h1: { fontSize: "48px", lineHeight: "58px", fontWeight: 600 /* Medium */ },- h2: {- fontSize: "32px",- lineHeight: "39px",- fontWeight: 500 /* Reset to regular to override MUI's default theme */,- },- h3: { fontSize: "24px", lineHeight: "29px", fontWeight: 600 /* Medium */ },- h4: {- fontSize: "22px",- lineHeight: "27px",- fontWeight: 500 /* Reset to regular to override MUI's default theme */,- },- h5: { fontSize: "20px", lineHeight: "25px", fontWeight: 600 /* Medium */ },- // h6 is the default variant used by MUI's DialogTitle.- h6: {- // The font size and line height below is the same as large.- fontSize: "18px",- lineHeight: "22px",- fontWeight: 600 /* Medium */,- },- body: { fontSize: "16px", lineHeight: "20px" },- small: { fontSize: "14px", lineHeight: "17px" },- mini: { fontSize: "12px", lineHeight: "15px" },- tiny: { fontSize: "10px", lineHeight: "12px" },-};--const getTypography = (appName: AppName): TypographyVariantsOptions => {- if (appName === "ensu") {- return {- ...baseTypography,- fontFamily:- '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',- // Ensu-specific variants (type-augmented in web/apps/ensu/src/types).- message: { fontSize: "15px", lineHeight: "1.7", fontWeight: 400 },- code: {- fontSize: "13px",- lineHeight: "1.45",- fontWeight: 400,- fontFamily:- 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',- },- } as TypographyVariantsOptions;- }- return baseTypography;-};--// Use the base typography for component style overrides (Button sizing, etc.).-const typography = baseTypography;--/**- * > [!NOTE]- * >- * > The theme isn't tree-shakeable, prefer creating new components for heavy- * > customization.- * >- * > https://mui.com/material-ui/customization/theme-components/- */-const components: Components = {- MuiCssBaseline: {- styleOverrides: {- body: {- // MUI has different letter spacing for each variant, but those- // are values arrived at for the default Material font, and- // don't work for the font that we're using.- //- // So we reset the letter spacing for _all_ variants to a- // reasonable value that works for our font.- letterSpacing: "-0.011em",- },- },- },-- MuiTypography: {- defaultProps: {- // MUI has body1 as the default variant for Typography, but our- // variant scheme is different, instead of body1/2, we have- // large/body/small etc. So reset the default to our equivalent of- // body1, which is "body".- variant: "body",- // Map all our custom variants to <p>.- variantMapping: { body: "p", small: "p", mini: "p", tiny: "p" },- },- },-- MuiModal: {- styleOverrides: {- root: {- // A workaround to prevent stuck modals from blocking clicks.- // https://github.com/mui/material-ui/issues/32286#issuecomment-1287951109- '&:has(> div[style*="opacity: 0"])': { pointerEvents: "none" },- },- },- },-- MuiDrawer: {- styleOverrides: {- root: {- ".MuiBackdrop-root": {- backgroundColor: "var(--mui-palette-backdrop-muted)",- },- },- },- },-- MuiDialog: {- defaultProps: {- // [Note: Workarounds for unactionable ARIA warnings]- //- // This is required to prevent console warnings about aria-hiding a- // focused button when the dialog is closed. e.g. Select a file,- // delete it. On closing the confirmation dialog, the error appears.- //- // The default is supposed to already be false, but setting this- // again seems to help. But sometimes we need to set this to `true`- // to prevent the warning. And sometimes neither helps, and we need- // to add random setTimeouts.- //- // Angular, Bootstrap, MUI, shadcn: all seem to be emitting these- // warning (just search the web). I'm don't know if this is just- // someone at Chrome deciding to emit spurious warnings without- // understanding the flow, or if none of these libraries have- // managed to implement the ARIA spec properly yet (which says more- // about the spec than about the libraries).- //- // - https://issues.chromium.org/issues/392121909- // - https://github.com/mui/material-ui/issues/43106#issuecomment-2314809028- closeAfterTransition: false,- },- styleOverrides: {- root: {- ".MuiBackdrop-root": {- backgroundColor: "var(--mui-palette-backdrop-muted)",- },- // Reset the MUI default paddings to 16px everywhere.- //- // This is not a great choice either, usually most dialogs, for- // one reason or the other, will need to customize this padding- // anyway. But not resetting it to 16px leaves it at the MUI- // defaults, which just doesn't work well with our designs.- "& .MuiDialogTitle-root": {- // MUI default is '16px 24px'.- padding: "16px",- },- "& .MuiDialogContent-root": {- // MUI default is '20px 24px'.- padding: "16px",- // If the contents of the dialog's contents exceed the- // available height, show a scrollbar just for the contents- // instead of the entire dialog.- overflowY: "auto",- },- "& .MuiDialogActions-root": {- // MUI default is way off for us since they cluster the- // buttons to the right, while our designs usually want the- // buttons to align with the heading / content.- padding: "16px",- },- ".MuiDialogTitle-root + .MuiDialogContent-root": {- // MUI resets this to 0 when the content doesn't use- // dividers (none of ours do). I feel that is a better- // default, since unlike margins, padding doesn't collapse,- // but changing this now would break existing layouts.- paddingTop: "16px",- },- },- },- },-- MuiPaper: {- styleOverrides: {- root: {- variants: [- {- // Use our "paper" shadow for elevated Paper.- props: { variant: "elevation" },- style: {- // MUI applies a semi-transparent background image- // for elevation in dark mode. Remove it to match- // background for our designs.- backgroundImage: "none",- // Use our paper shadow.- boxShadow: "var(--mui-palette-boxShadow-paper)",- },- },- {- // Undo the effects of variant "elevation" case above- // case when elevation is 0.- props: { elevation: 0 },- style: { boxShadow: "none" },- },- ],- },- },- },-- // The default link "color" prop is "primary", which maps to "fill.base"- // (and equivalently, to "text.base"). In our current designs, the <Link>- // MUI component is only used in places where the surrounding text uses- // "text.muted", so this default already provides it a highlight compared to- // the text it in embedded in.- //- // We additionally disable the underline, and add a hover indication by- // switching its color to the main accent.- MuiLink: {- defaultProps: { underline: "none" },- styleOverrides: {- root: { "&:hover": { color: "var(--mui-palette-accent-main)" } },- },- },-- MuiButton: {- defaultProps: {- // Change the default button variant from "text" to "contained".- variant: "contained",- // Disable shadows.- disableElevation: true,- },- styleOverrides: {- // We don't use the size prop for the MUI button, or rather it- // cannot be used, since we have fixed the paddings and font sizes- // unconditionally here (which is all that the size prop changes).- root: {- padding: "12px 16px",- borderRadius: "4px",- textTransform: "none",- // Body, but medium.- fontSize: typography.body?.fontSize,- lineHeight: typography.body?.lineHeight,- fontWeight: 600,- },- startIcon: { marginRight: "12px", "&& >svg": { fontSize: "20px" } },- endIcon: { marginLeft: "12px", "&& >svg": { fontSize: "20px" } },- },- },-- MuiInputBase: {- styleOverrides: {- formControl: {- // Give a symmetric border to the input field, by default the- // border radius is only applied to the top for the "filled"- // variant of input used inside TextFields.- borderRadius: "8px",- // Clip the bottom border so that there is no gap between the- // filled area and the (full width) border.- overflow: "hidden",- // Hide the bottom border that always appears for the "filled"- // variant of input used inside TextFields.- "::before": { borderBottom: "none !important" },- },- },- },-- MuiTextField: {- defaultProps: {- // The MUI default variant is "outlined", override it to use the- // "filled" one by default.- variant: "filled",- // Reduce the vertical margins that MUI adds to the TextField.- //- // Note that this causes things to be too tight when the helper text- // is shown, so this is not recommended for new code that we write.- margin: "dense",- },- styleOverrides: {- root: { "& .MuiInputAdornment-root": { marginRight: "8px" } },- },- },-- MuiCheckbox: {- defaultProps: {- // Disable the ripple effect for all checkboxes.- disableRipple: true,- },- styleOverrides: {- // Since we've disabled the ripple, add other affordances to it (a- // background and outline) to clearly indicate whenever it gains- // keyboard focus.- root: {- "&.Mui-focusVisible": {- backgroundColor: "var(--mui-palette-fill-faint)",- outline: "1px solid var(--mui-palette-stroke-faint)",- },- },- },- },-- MuiSvgIcon: {- styleOverrides: {- root: {- variants: [- {- props: { color: "primary" },- style: { color: "var(--mui-palette-stroke-base)" },- },- {- props: { color: "secondary" },- style: { color: "var(--mui-palette-stroke-muted)" },- },- ],- },- },- },-- MuiIconButton: {- styleOverrides: {- root: {- padding: "12px",- variants: [- {- props: { color: "primary" },- style: { color: "var(--mui-palette-stroke-base)" },- },- {- props: { color: "secondary" },- style: { color: "var(--mui-palette-stroke-muted)" },- },- ],- "&.Mui-disabled": { color: "var(--mui-palette-stroke-faint)" },- },- },- },-- MuiMenu: {- styleOverrides: {- root: {- ".MuiMenu-paper": {- boxShadow: "var(--mui-palette-boxShadow-menu)",- },- },- },- },-- MuiSnackbar: {- styleOverrides: {- root: {- // Set a default border radius for all snackbar's (e.g.- // notification popups).- borderRadius: "8px",- },- },- },-- MuiAlert: {- defaultProps: {- // Use the outlined variant by default (instead of "standard").- variant: "outlined",- },- },-};--const getComponents = (appName: AppName): Components => {- if (appName !== "ensu" && appName !== "locker") return components;-- const muiButtonStyleOverrides = (components.MuiButton?.styleOverrides ??- {}) as Record<string, unknown>;- const muiButtonRootStyleOverrides =- (muiButtonStyleOverrides.root as Record<string, unknown> | undefined) ??- {};- const muiIconButtonStyleOverrides = (components.MuiIconButton- ?.styleOverrides ?? {}) as Record<string, unknown>;- const muiIconButtonRootStyleOverrides =- (muiIconButtonStyleOverrides.root as- | Record<string, unknown>- | undefined) ?? {};- const muiInputBaseStyleOverrides = (components.MuiInputBase- ?.styleOverrides ?? {}) as Record<string, unknown>;- const muiInputBaseFormControlStyleOverrides =- (muiInputBaseStyleOverrides.formControl as- | Record<string, unknown>- | undefined) ?? {};- const muiDialogTitleStyleOverrides = (components.MuiDialogTitle- ?.styleOverrides ?? {}) as Record<string, unknown>;- const muiDialogContentStyleOverrides = (components.MuiDialogContent- ?.styleOverrides ?? {}) as Record<string, unknown>;-- if (appName === "locker") {- return {- ...components,- MuiButton: {- ...components.MuiButton,- styleOverrides: {- ...muiButtonStyleOverrides,- root: {- ...muiButtonRootStyleOverrides,- borderRadius: "20px",- },- } as NonNullable<- NonNullable<Components["MuiButton"]>["styleOverrides"]- >,- },- MuiIconButton: {- ...components.MuiIconButton,- styleOverrides: {- ...muiIconButtonStyleOverrides,- root: {- ...muiIconButtonRootStyleOverrides,- borderRadius: "18px",- },- } as NonNullable<- NonNullable<Components["MuiIconButton"]>["styleOverrides"]- >,- },- MuiInputBase: {- ...components.MuiInputBase,- styleOverrides: {- ...muiInputBaseStyleOverrides,- formControl: {- ...muiInputBaseFormControlStyleOverrides,- borderRadius: "16px",- },- } as NonNullable<- NonNullable<Components["MuiInputBase"]>["styleOverrides"]- >,- },- MuiOutlinedInput: {- ...components.MuiOutlinedInput,- styleOverrides: {- ...components.MuiOutlinedInput?.styleOverrides,- root: {- ...(components.MuiOutlinedInput?.styleOverrides- ?.root as Record<string, unknown> | undefined),- borderRadius: "16px",- },- } as NonNullable<- NonNullable<- Components["MuiOutlinedInput"]- >["styleOverrides"]- >,- },- MuiFilledInput: {- ...components.MuiFilledInput,- styleOverrides: {- ...components.MuiFilledInput?.styleOverrides,- root: {- ...(components.MuiFilledInput?.styleOverrides?.root as- | Record<string, unknown>- | undefined),- borderRadius: "16px",- },- } as NonNullable<- NonNullable<Components["MuiFilledInput"]>["styleOverrides"]- >,- },- MuiDialogTitle: {- ...components.MuiDialogTitle,- styleOverrides: {- ...muiDialogTitleStyleOverrides,- root: {- ...(muiDialogTitleStyleOverrides.root as- | Record<string, unknown>- | undefined),- paddingBottom: "12px",- },- } as NonNullable<- NonNullable<Components["MuiDialogTitle"]>["styleOverrides"]- >,- },- MuiDialogContent: {- ...components.MuiDialogContent,- styleOverrides: {- ...muiDialogContentStyleOverrides,- root: {- ...(muiDialogContentStyleOverrides.root as- | Record<string, unknown>- | undefined),- paddingTop: "8px",- },- } as NonNullable<- NonNullable<- Components["MuiDialogContent"]- >["styleOverrides"]- >,- },- };- }-- return {- ...components,- MuiTypography: {- ...components.MuiTypography,- defaultProps: {- ...components.MuiTypography?.defaultProps,- variantMapping: {- ...components.MuiTypography?.defaultProps?.variantMapping,- message: "p",- code: "code",- } as Record<string, string>,- },- },- MuiButton: {- ...components.MuiButton,- styleOverrides: {- ...muiButtonStyleOverrides,- root: { ...muiButtonRootStyleOverrides, borderRadius: "16px" },- } as NonNullable<- NonNullable<Components["MuiButton"]>["styleOverrides"]- >,- },- };-};--// Exports -----export const photosTheme = getTheme("photos");diff --git a/web/apps/albums/vendor/ente-base/context.ts b/web/apps/albums/vendor/ente-base/context.tsdeleted file mode 100644index 19ed2f023a..0000000000--- a/web/apps/albums/vendor/ente-base/context.ts+++ /dev/null@@ -1,62 +0,0 @@-import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";-import { createContext, useContext } from "react";-import { genericErrorDialogAttributes } from "./components/utils/dialog";-import log from "./log";--/**- * The type of the context expected to be present in the React tree for all apps- * that use the base package.- *- * It is usually provided by the _app.tsx for the corresponding app.- */-export interface BaseContextT {- /**- * Show a "mini dialog" with the given attributes.- *- * Mini dialogs (see {@link AttributedMiniDialog}) are meant for simple- * confirmation or notifications. Their appearance and functionality can be- * customized by providing appropriate {@link MiniDialogAttributes}.- */- showMiniDialog: (attributes: MiniDialogAttributes) => void;- /**- * Log the given error and show a generic error {@link MiniDialog}.- */- onGenericError: (error: unknown) => void;-}--/**- * The React {@link Context} of type {@link BaseContextT} available to all React- * components that refer to the base package.- */-export const BaseContext = createContext<BaseContextT | undefined>(undefined);--/**- * Utility hook to get the required {@link BaseContextT} that is expected to be- * available to all React components that refer to the base package.- */-export const useBaseContext = (): BaseContextT => useContext(BaseContext)!;--/**- * A helper function to create a {@link BaseContext} by deriving the generic- * error handler from the provided {@link showMiniDialog}.- *- * In simpler words, it automatically provides a definition of- * {@link onGenericError} using the given {@link showMiniDialog} prop.- */-export const deriveBaseContext = ({- showMiniDialog,-}: Omit<BaseContextT, "onGenericError">): BaseContextT => {- const onGenericError = (e: unknown) => {- log.error(e);- // The generic error handler is sometimes called in the context of- // actions that were initiated by a confirmation dialog action handler- // themselves, then we need to let the current one close.- //- // See: [Note: Chained MiniDialogs]- setTimeout(() => {- showMiniDialog(genericErrorDialogAttributes());- }, 0);- };-- return { showMiniDialog, onGenericError };-};diff --git a/web/apps/albums/vendor/ente-base/crypto/index.ts b/web/apps/albums/vendor/ente-base/crypto/index.tsdeleted file mode 100644index cf837db59c..0000000000--- a/web/apps/albums/vendor/ente-base/crypto/index.ts+++ /dev/null@@ -1,531 +0,0 @@-/**- * @file Cryptographic operations. This is the highest layer of the crypto code- * hierarchy, and is meant to be used directly by the rest of our code.- *- * --|- * --> For each function, more detailed documentation is in `libsodium.ts` <-- * --|- *- * [Note: Crypto code hierarchy]- *- * 1. ente-base/crypto (Crypto API for our code)- * 2. ente-base/crypto/libsodium (The actual implementation)- * 3. libsodium-wrappers (JavaScript bindings to libsodium)- *- * Our cryptography primitives are provided by libsodium, specifically, its- * JavaScript bindings ("libsodium-wrappers"). That is the lowest layer.- *- * > Note that we use the sumo variant, "libsodium-wrappers-sumo", since the- * standard variant does not provide the `crypto_pwhash_*` functions.- *- * Direct usage of "libsodium-wrappers" is restricted to `crypto/libsodium.ts`.- * That is the next higher layer. Usually the functions in this file are thin- * wrappers over the raw libsodium APIs, with a bit of massaging. They also- * ensure that sodium.ready has been called before accessing libsodium's APIs,- * thus all the functions it exposes are async.- *- * Direct usage of "libsodium-wrappers" is restricted to this file,- * `crypto/index.ts`. This is the highest layer. These are direct proxies to- * functions exposed by `crypto/libsodium.ts`, but they automatically defer to a- * worker thread if we're not already running on one. More on this below.- *- * ---- *- * [Note: Using libsodium in worker thread]- *- * This file, `crypto/index.ts`, and `crypto/worker.ts` are mostly logic-less- * trampolines meant to allow us to seamlessly use the the same API both from- * the main thread or from a web worker whilst ensuring that the implementation- * never runs on the main thread.- *- * Cryptographic operations like encryption are CPU intensive and would cause- * the UI to stutter if used directly on the main thread. To keep the UI smooth,- * we instead want to run them in a web worker. However, sometimes we already- * _are_ running in a web worker, and delegating to another worker is wasteful.- *- * The external API functions provided by this file check to see if we're- * already in a web worker, and if so directly invoke the implementation.- * Otherwise the call the sibling function in a shared "crypto" web worker- * (which then invokes the implementation function, but this time in the context- * of a web worker).- *- * As a consumer, it is safe to just call functions in this file, and they'll- * just do the right thing based on the context. However, it is also fine to- * explicitly get an handle to a crypto web worker and use that. e.g., the- * uploader creates it own crypto worker instances and directly calls the- * functions in the workers that it created instead of going through this file.- *- * ---- *- * [Note: Crypto layer API data types]- *- * There are two primary types used when exchanging data with these functions:- *- * 1. Base64 strings. Unless stated otherwise, all strings are taken as base64- * encoded representations of the underlying data. Usually, the unqualified- * function deals with base64 strings, since they also are the data type in- * which we usually store and send the data.- *- * 2. Raw bytes. Uint8Arrays are byte arrays. The functions that deal with bytes- * are usually indicated by a *Bytes suffix in their name, but not always- * since it might also be the natural choice for functions that deal with- * larger amounts of data.- *- * Where relevant and useful, functions also accept a union of these two - a- * {@link BytesOrB64} where the implementation will automatically convert- * to/from base64 to bytes if needed, thus saving on unnecessary conversions at- * the caller side.- *- * Apart from these two, there are other secondary, one off types.- *- * 1. Hex representations of the bytes. These are indicated by the *Hex suffix- * on the functions dealing with them.- *- * 2. JSON values. These are indicated by the *JSON suffix on the functions- * dealing with them.- */-import { ComlinkWorker } from "ente-base/worker/comlink-worker";-import { inWorker } from "../env";-import * as libsodium from "./libsodium";-import type {- BytesOrB64,- DerivedKey,- EncryptedBlob,- EncryptedBlobB64,- EncryptedBlobBytes,- EncryptedBox,- EncryptedBoxB64,- EncryptedFile,- InitChunkDecryptionResult,- InitChunkEncryptionResult,- KeyPair,- SodiumStateAddress,-} from "./types";-import type { CryptoWorker } from "./worker";--/**- * Cached instance of the {@link ComlinkWorker} that wraps our web worker.- */-let _comlinkWorker: ComlinkWorker<typeof CryptoWorker> | undefined;--/**- * Lazily created, cached, instance of a "shared" CryptoWorker web worker.- *- * Some code which needs to do operations in parallel (e.g. during the upload- * flow) creates its own CryptoWorker web workers. But those are exceptions; the- * rest of the code normally calls the functions in this file, and they all- * implicitly use a default "shared" web worker (unless we're already running in- * the context of a web worker).- */-const sharedWorker = () =>- (_comlinkWorker ??= createComlinkCryptoWorker()).remote;--/**- * Create a new instance of a comlink worker that wraps a {@link CryptoWorker}- * web worker.- */-export const createComlinkCryptoWorker = () =>- new ComlinkWorker<typeof CryptoWorker>(- "crypto",- new Worker(new URL("worker.ts", import.meta.url)),- );--/**- * Convert bytes ({@link Uint8Array}) to a base64 string.- */-export const toB64 = (bytes: Uint8Array): Promise<string> =>- inWorker()- ? libsodium.toB64(bytes)- : sharedWorker().then((w) => w.toB64(bytes));--/**- * Convert a base64 string to bytes ({@link Uint8Array}).- */-export const fromB64 = (b64String: string): Promise<Uint8Array> =>- inWorker()- ? libsodium.fromB64(b64String)- : sharedWorker().then((w) => w.fromB64(b64String));--/**- * URL safe variant of {@link toB64}.- */-export const toB64URLSafe = (bytes: Uint8Array): Promise<string> =>- inWorker()- ? libsodium.toB64URLSafe(bytes)- : sharedWorker().then((w) => w.toB64URLSafe(bytes));--/**- * URL safe variant of {@link toB64} that does not add any padding ("="- * characters).- */-export const toB64URLSafeNoPadding = (bytes: Uint8Array): Promise<string> =>- inWorker()- ? libsodium.toB64URLSafeNoPadding(bytes)- : sharedWorker().then((w) => w.toB64URLSafeNoPadding(bytes));--/**- * URL safe unpadded variant of {@link fromB64}.- */-export const fromB64URLSafeNoPadding = (- b64String: string,-): Promise<Uint8Array> =>- inWorker()- ? libsodium.fromB64URLSafeNoPadding(b64String)- : sharedWorker().then((w) => w.fromB64URLSafeNoPadding(b64String));--/**- * Convert a base64 string to the hex representation of the underlying bytes.- */-export const toHex = (b64String: string): Promise<string> =>- inWorker()- ? libsodium.toHex(b64String)- : sharedWorker().then((w) => w.toHex(b64String));--/**- * Convert a hex string to the base64 representation of the underlying bytes.- */-export const fromHex = (hexString: string): Promise<string> =>- inWorker()- ? libsodium.fromHex(hexString)- : sharedWorker().then((w) => w.fromHex(hexString));--/**- * Return a new randomly generated 256-bit key (as a base64 string).- *- * The returned key is suitable for use with the *Box encryption functions, and- * as a general encryption key (e.g. as the user's master key or recovery key).- */-export const generateKey = (): Promise<string> =>- inWorker()- ? libsodium.generateKey()- : sharedWorker().then((w) => w.generateKey());--/**- * Return a new randomly generated 256-bit key (as a base64 string) suitable for- * use with the *Blob or *Stream encryption functions.- */-export const generateBlobOrStreamKey = (): Promise<string> =>- inWorker()- ? libsodium.generateBlobOrStreamKey()- : sharedWorker().then((w) => w.generateBlobOrStreamKey());--/**- * Encrypt the given data, returning a box containing the encrypted data and a- * randomly generated nonce that was used during encryption.- *- * Both the encrypted data and the nonce are returned as base64 strings.- *- * Use {@link decryptBox} to decrypt the result.- *- * > The suffix "Box" comes from the fact that it uses the so called secretbox- * > APIs provided by libsodium under the hood.- * >- * > See: [Note: 3 forms of encryption (Box | Blob | Stream)]- */-export const encryptBox = (- data: BytesOrB64,- key: BytesOrB64,-): Promise<EncryptedBoxB64> =>- inWorker()- ? libsodium.encryptBox(data, key)- : sharedWorker().then((w) => w.encryptBox(data, key));--/**- * Encrypt the given data, returning a blob containing the encrypted data and a- * decryption header as base64 strings.- *- * This function is usually used to encrypt data associated with an Ente object- * (file, collection, entity) using the object's key.- *- * Use {@link decryptBlob} or {@link decryptBlobBytes} to decrypt the result.- *- * > The suffix "Blob" comes from our convention of naming functions that use- * > the secretstream APIs without breaking the data into chunks.- * >- * > See: [Note: 3 forms of encryption (Box | Blob | Stream)]- */-export const encryptBlob = (- data: BytesOrB64,- key: BytesOrB64,-): Promise<EncryptedBlobB64> =>- inWorker()- ? libsodium.encryptBlob(data, key)- : sharedWorker().then((w) => w.encryptBlob(data, key));--/**- * A variant of {@link encryptBlob} that returns the result components as bytes- * instead of as base64 strings.- *- * Use {@link decryptBlob} or {@link decryptBlobBytes} to decrypt the result.- */-export const encryptBlobBytes = (- data: BytesOrB64,- key: BytesOrB64,-): Promise<EncryptedBlobBytes> =>- inWorker()- ? libsodium.encryptBlobBytes(data, key)- : sharedWorker().then((w) => w.encryptBlobBytes(data, key));--/**- * Encrypt the JSON metadata associated with an Ente object (file, collection or- * entity) using the object's key.- *- * This is a variant of {@link encryptBlob} tailored for encrypting any- * arbitrary metadata associated with an Ente object. For example, it is used- * for encrypting the various metadata fields associated with a file, using that- * file's key.- *- * Instead of raw bytes, it takes as input an arbitrary JSON object which it- * encodes into a string, and encrypts that.- *- * Use {@link decryptMetadataJSON} to decrypt the result.- *- * @param jsonValue The JSON value to encrypt. This can be an arbitrary JSON- * value, but since TypeScript currently doesn't have a native JSON type, it is- * typed as {@link unknown}.- *- * @param key The encryption key.- */-export const encryptMetadataJSON = (- jsonValue: unknown,- key: BytesOrB64,-): Promise<EncryptedBlobB64> =>- inWorker()- ? libsodium.encryptMetadataJSON(jsonValue, key)- : sharedWorker().then((w) => w.encryptMetadataJSON(jsonValue, key));--/**- * Encrypt the given data using chunked streaming encryption, but process all- * the chunks in one go.- */-export const encryptStreamBytes = (- data: Uint8Array,- key: BytesOrB64,-): Promise<EncryptedFile> =>- inWorker()- ? libsodium.encryptStreamBytes(data, key)- : sharedWorker().then((w) => w.encryptStreamBytes(data, key));--/**- * Prepare for chunked streaming encryption using {@link encryptStreamChunk}.- */-export const initChunkEncryption = (- key: BytesOrB64,-): Promise<InitChunkEncryptionResult> =>- inWorker()- ? libsodium.initChunkEncryption(key)- : sharedWorker().then((w) => w.initChunkEncryption(key));--/**- * Encrypt a chunk as part of a chunked streaming encryption.- */-export const encryptStreamChunk = (- data: Uint8Array,- state: SodiumStateAddress,- isFinalChunk: boolean,-): Promise<Uint8Array> =>- inWorker()- ? libsodium.encryptStreamChunk(data, state, isFinalChunk)- : sharedWorker().then((w) =>- w.encryptStreamChunk(data, state, isFinalChunk),- );--/**- * Decrypt a box encrypted using {@link encryptBox} and returns the decrypted- * bytes as a base64 string.- */-export const decryptBox = (- box: EncryptedBox,- key: BytesOrB64,-): Promise<string> =>- inWorker()- ? libsodium.decryptBox(box, key)- : sharedWorker().then((w) => w.decryptBox(box, key));--/**- * Variant of {@link decryptBox} that returns the decrypted bytes as it is- * (without encoding them to base64).- */-export const decryptBoxBytes = (- box: EncryptedBox,- key: BytesOrB64,-): Promise<Uint8Array> =>- inWorker()- ? libsodium.decryptBoxBytes(box, key)- : sharedWorker().then((w) => w.decryptBoxBytes(box, key));--/**- * Decrypt a blob encrypted using either {@link encryptBlobBytes} or- * {@link encryptBlob} and return it as a base64 encoded string.- */-export const decryptBlob = (- blob: EncryptedBlob,- key: BytesOrB64,-): Promise<string> =>- inWorker()- ? libsodium.decryptBlob(blob, key)- : sharedWorker().then((w) => w.decryptBlob(blob, key));--/**- * A variant of {@link decryptBlobBytes} that returns the result bytes directly- * (instead of encoding them as a base64 string).- */-export const decryptBlobBytes = (- blob: EncryptedBlob,- key: BytesOrB64,-): Promise<Uint8Array> =>- inWorker()- ? libsodium.decryptBlobBytes(blob, key)- : sharedWorker().then((w) => w.decryptBlobBytes(blob, key));--/**- * Decrypt the result of {@link encryptStreamBytes}.- */-export const decryptStreamBytes = (- file: EncryptedFile,- key: BytesOrB64,-): Promise<Uint8Array> =>- inWorker()- ? libsodium.decryptStreamBytes(file, key)- : sharedWorker().then((w) => w.decryptStreamBytes(file, key));--/**- * Prepare to decrypt the encrypted result produced using {@link initChunkEncryption} and- * {@link encryptStreamChunk}.- */-export const initChunkDecryption = (- header: string,- key: BytesOrB64,-): Promise<InitChunkDecryptionResult> =>- inWorker()- ? libsodium.initChunkDecryption(header, key)- : sharedWorker().then((w) => w.initChunkDecryption(header, key));--/**- * Decrypt an individual chunk produced by {@link encryptStreamChunk}.- *- * This function is used in tandem with {@link initChunkDecryption}.- */-export const decryptStreamChunk = (- data: Uint8Array,- state: SodiumStateAddress,-): Promise<Uint8Array> =>- inWorker()- ? libsodium.decryptStreamChunk(data, state)- : sharedWorker().then((w) => w.decryptStreamChunk(data, state));--/**- * Decrypt the metadata JSON encrypted using {@link encryptMetadataJSON}.- *- * @returns The decrypted JSON value. Since TypeScript does not have a native- * JSON type, we need to return it as an `unknown`.- */-export const decryptMetadataJSON = (- blob: EncryptedBlob,- key: BytesOrB64,-): Promise<unknown> =>- inWorker()- ? libsodium.decryptMetadataJSON(blob, key)- : sharedWorker().then((w) => w.decryptMetadataJSON(blob, key));--/**- * Generate a new public/private keypair.- */-export const generateKeyPair = (): Promise<KeyPair> =>- inWorker()- ? libsodium.generateKeyPair()- : sharedWorker().then((w) => w.generateKeyPair());--/**- * Public key encryption.- */-export const boxSeal = (data: string, publicKey: string): Promise<string> =>- inWorker()- ? libsodium.boxSeal(data, publicKey)- : sharedWorker().then((w) => w.boxSeal(data, publicKey));--/**- * Decrypt the result of {@link boxSeal}.- */-export const boxSealOpen = (- encryptedData: string,- keyPair: KeyPair,-): Promise<string> =>- inWorker()- ? libsodium.boxSealOpen(encryptedData, keyPair)- : sharedWorker().then((w) => w.boxSealOpen(encryptedData, keyPair));--/**- * Variant of {@link boxSealOpen} that returns the decrypted bytes as it is- * (without encoding them to base64).- */-export const boxSealOpenBytes = (- encryptedData: string,- keyPair: KeyPair,-): Promise<Uint8Array> =>- inWorker()- ? libsodium.boxSealOpenBytes(encryptedData, keyPair)- : sharedWorker().then((w) =>- w.boxSealOpenBytes(encryptedData, keyPair),- );--/**- * Return a new randomly generated 128-bit salt (as a base64 string).- *- * The returned salt is suitable for use with {@link deriveKey}, and also as a- * general 128-bit salt.- */-export const generateDeriveKeySalt = (): Promise<string> =>- inWorker()- ? libsodium.generateDeriveKeySalt()- : sharedWorker().then((w) => w.generateDeriveKeySalt());--/**- * Derive a key by hashing the given {@link passphrase} using Argon 2id.- */-export const deriveKey = (- passphrase: string,- salt: string,- opsLimit: number,- memLimit: number,-): Promise<string> =>- inWorker()- ? libsodium.deriveKey(passphrase, salt, opsLimit, memLimit)- : sharedWorker().then((w) =>- w.deriveKey(passphrase, salt, opsLimit, memLimit),- );--/**- * Derive a sensitive key from the given {@link passphrase}.- */-export const deriveSensitiveKey = (passphrase: string): Promise<DerivedKey> =>- inWorker()- ? libsodium.deriveSensitiveKey(passphrase)- : sharedWorker().then((w) => w.deriveSensitiveKey(passphrase));--/**- * Derive an key suitable for interactive use from the given {@link passphrase}.- */-export const deriveInteractiveKey = (- passphrase: string,-): Promise<DerivedKey> =>- inWorker()- ? libsodium.deriveInteractiveKey(passphrase)- : sharedWorker().then((w) => w.deriveInteractiveKey(passphrase));--/**- * Derive a subkey of the given {@link key} using the specified parameters.- *- * @returns the bytes of the derived subkey.- */-export const deriveSubKeyBytes = async (- key: string,- subKeyLength: number,- subKeyID: number,- context: string,-): Promise<Uint8Array> =>- inWorker()- ? libsodium.deriveSubKeyBytes(key, subKeyLength, subKeyID, context)- : sharedWorker().then((w) =>- w.deriveSubKeyBytes(key, subKeyLength, subKeyID, context),- );diff --git a/web/apps/albums/vendor/ente-base/crypto/libsodium.ts b/web/apps/albums/vendor/ente-base/crypto/libsodium.tsdeleted file mode 100644index 18129942d3..0000000000--- a/web/apps/albums/vendor/ente-base/crypto/libsodium.ts+++ /dev/null@@ -1,900 +0,0 @@-/**- * @file A thin-ish layer over the actual libsodium APIs, to make them more- * palatable to the rest of our Javascript code.- *- * All functions are stateless, async, and safe to use in Web Workers.- *- * Docs for the JS library: https://github.com/jedisct1/libsodium.js.- *- * To see where this code fits, see [Note: Crypto code hierarchy].- */-import { mergeUint8Arrays } from "ente-utils/array";-import sodium from "libsodium-wrappers-sumo";-import {- deriveKeyInsufficientMemoryErrorMessage,- streamEncryptionChunkSize,- type BytesOrB64,- type DerivedKey,- type EncryptedBlob,- type EncryptedBlobB64,- type EncryptedBlobBytes,- type EncryptedBox,- type EncryptedBoxB64,- type EncryptedFile,- type InitChunkDecryptionResult,- type InitChunkEncryptionResult,- type KeyPair,- type SodiumStateAddress,-} from "./types";--/**- * Convert bytes ({@link Uint8Array}) to a base64 string.- *- * See also {@link toB64URLSafe} and {@link toB64URLSafeNoPadding}.- */-export const toB64 = async (input: Uint8Array) => {- await sodium.ready;- return sodium.to_base64(input, sodium.base64_variants.ORIGINAL);-};--/**- * Convert a base64 string to bytes ({@link Uint8Array}).- *- * This is the converse of {@link toBase64}.- */-export const fromB64 = async (input: string): Promise<Uint8Array> => {- await sodium.ready;- return sodium.from_base64(input, sodium.base64_variants.ORIGINAL);-};--/**- * Convert bytes ({@link Uint8Array}) to a URL-safe base64 string.- *- * See also {@link toB64URLSafe} and {@link toB64URLSafeNoPadding}.- */-export const toB64URLSafe = async (input: Uint8Array) => {- await sodium.ready;- return sodium.to_base64(input, sodium.base64_variants.URLSAFE);-};--/**- * Convert bytes ({@link Uint8Array}) to a unpadded URL-safe base64 string.- *- * This differs from {@link toB64URLSafe} in that it does not append any- * trailing padding character(s) "=" to make the resultant string's length be an- * integer multiple of 4.- *- * - In some contexts, for example when serializing WebAuthn binary for- * transmission over the network, this is the required / recommended approach.- *- * - In other cases, for example when trying to pass an arbitrary JSON string- * via a URL parameter, this is also convenient so that we do not have to deal- * with any ambiguity surrounding the "=" which is also the query parameter- * key value separator.- */-export const toB64URLSafeNoPadding = async (input: Uint8Array) => {- await sodium.ready;- return sodium.to_base64(input, sodium.base64_variants.URLSAFE_NO_PADDING);-};--/**- * Convert a unpadded URL-safe base64 string to bytes ({@link Uint8Array}).- *- * This is the converse of {@link toB64URLSafeNoPadding}, and does not expect- * its input string's length to be a an integer multiple of 4.- */-export const fromB64URLSafeNoPadding = async (input: string) => {- await sodium.ready;- return sodium.from_base64(input, sodium.base64_variants.URLSAFE_NO_PADDING);-};--/**- * Convert a base64 string to the hex representation of the bytes that the base- * 64 string encodes.- *- * Use {@link fromHex} to go back.- */-export const toHex = async (input: string) => {- await sodium.ready;- return sodium.to_hex(await fromB64(input));-};--/**- * Convert a hex string to the base64 representation of the bytes that the hex- * string encodes.- *- * This is the inverse of {@link toHex}.- */-export const fromHex = async (input: string): Promise<string> => {- await sodium.ready;- return await toB64(sodium.from_hex(input));-};--/**- * If the provided {@link bob} ("Bytes or B64 string") is already a- * {@link Uint8Array}, return it unchanged, otherwise convert the base64 string- * into bytes and return those.- */-const bytes = async (bob: BytesOrB64) =>- typeof bob == "string" ? fromB64(bob) : bob;--/**- * Generate a new randomly generated 256-bit key for use as a general encryption- * key and return its base64 string representation.- *- * From the architecture docs:- *- * > [`crypto_secretbox_keygen`](https://libsodium.gitbook.io/doc/public-key_cryptography/sealed_boxes)- * > is used to generate all random keys within the application. Your- * > `masterKey`, `recoveryKey`, `collectionKey`, `fileKey` are all 256-bit keys- * > generated using this API.- *- * {@link generateKey} can be contrasted with {@link generateBlobOrStreamKey}- * and can be thought of as a hypothetical "generateBoxKey". That is, the key- * returned by this function is suitable for being used with the *Box encryption- * functions (which eventually delegate to the libsodium's secretbox APIs).- *- * While this is a reasonable semantic distinction, in terms of implementation- * there is no difference: currently both {@link generateKey} (or the- * hypothetical "generateBoxKey") and {@link generateBlobOrStreamKey} produce- * 256-bits of entropy that does not have any ties to a particular algorithm.- *- * @returns A new randomly generated 256-bit key (as a base64 string).- */-export const generateKey = async () => {- await sodium.ready;- return toB64(sodium.crypto_secretbox_keygen());-};--/**- * Generate a new key for use with the *Blob or *Stream encryption functions,- * and return its base64 string representation.- *- * This returns a new randomly generated 256-bit key (as a base64 string)- * suitable for being used with libsodium's secretstream APIs.- */-export const generateBlobOrStreamKey = async () => {- await sodium.ready;- return toB64(sodium.crypto_secretstream_xchacha20poly1305_keygen());-};--/**- * Encrypt the given data using libsodium's secretbox APIs, using a randomly- * generated nonce.- *- * Use {@link decryptBox} or {@link decryptBoxBytes} to decrypt the result.- *- * @param data The data to encrypt.- *- * @param key The key to use for encryption.- *- * @returns The encrypted data and the generated nonce, both as base64 strings.- *- * [Note: 3 forms of encryption (Box | Blob | Stream)]- *- * libsodium provides two "high level" encryption patterns:- *- * 1. Authenticated encryption ("secretbox")- * https://doc.libsodium.org/secret-key_cryptography/secretbox- *- * 2. Encrypted streams and file encryption ("secretstream")- * https://doc.libsodium.org/secret-key_cryptography/secretstream- *- * In terms of the underlying algorithm, they are essentially the same.- *- * 1. The secretbox APIs use XSalsa20 with Poly1305 (where XSalsa20 is the- * stream cipher used for encryption, which Poly1305 is the MAC used for- * authentication).- *- * 2. The secretstream APIs use XChaCha20 with Poly1305.- *- * XSalsa20 is a minor variant (predecessor in fact) of XChaCha20. I am not- * aware why libsodium uses both the variants, but they seem to have similar- * characteristics.- *- * These two sets of APIs map functionally map to two different use cases.- *- * 1. If there is a single independent bit of data to encrypt, the secretbox- * APIs fit the bill.- *- * 2. If there is a set of related data to encrypt, e.g. the contents of a file- * where the file is too big to fit into a single message, then the- * secretstream APIs are more appropriate.- *- * However, in our code we have evolved two different use cases for the 2nd- * option. The data to encrypt might be smaller than our streaming encryption- * chunk size (e.g. the public magic metadata associated with the- * {@link EnteFile}), so we do not chunk it and instead encrypt / decrypt it in- * a single go. In contrast, the actual file that the user wishes to upload may- * be arbitrarily big, and there we first break in into chunks before using the- * streaming encryption.- *- * Thus, we have three scenarios:- *- * 1. Box: Using secretbox APIs to encrypt some independent blob of data.- *- * 2. Blob: Using secretstream APIs without chunking. This is used to encrypt- * data associated to an Ente object (file, collection, entity, etc), when- * the data is small-ish (less than a few MBs).- *- * 3. Stream/Chunks: Using secretstream APIs for encrypting chunks. This is used- * to encrypt the actual content of the files associated with an EnteFile- * object. This itself happens in two ways:- *- * 3a. One shot mode - where we do break the data into chunks, but a single- * function processes all the chunks in one go.- *- * 3b. Streaming - where all the chunks are processed one by one.- *- * "Blob" is not a prior term of art in this context, it is just something we- * use to abbreviate "data encrypted using secretstream APIs without chunking".- *- * The distinction between Box and Blob is also handy since not only does the- * underlying algorithm differ, but also the terminology that libsodium use for- * the nonce.- *- * 1. When using the secretbox APIs, the nonce is called the "nonce", and needs- * to be provided by us (the caller).- *- * 2. When using the secretstream APIs, the nonce is internally generated by- * libsodium and provided by libsodium to us (the caller) as a "header".- *- * However, even for case 1, the functions we expose from libsodium.ts generate- * the nonce for the caller. So for higher level functions, the difference- * between Box and Blob encryption is:- *- * 1. Box uses secretbox APIs (Salsa), Blob uses secretstream APIs (ChaCha).- *- * 2. Blob should generally be used for data associated with an Ente object, and- * Box for the other cases.- *- * 3. Box returns a "nonce", while Blob returns a "header".- *- * The difference between case 2 and 3 (Blob vs Stream) is that while both use- * the same algorithms, in case of Blob the entire data is encrypted / decrypted- * without chunking, whilst the *Stream routines first break it into- * {@link streamEncryptionChunkSize} chunks.- */-export const encryptBox = async (- data: BytesOrB64,- key: BytesOrB64,-): Promise<EncryptedBoxB64> => {- await sodium.ready;- const nonce = sodium.randombytes_buf(sodium.crypto_secretbox_NONCEBYTES);- const encryptedData = sodium.crypto_secretbox_easy(- await bytes(data),- nonce,- await bytes(key),- );- return {- encryptedData: await toB64(encryptedData),- nonce: await toB64(nonce),- };-};--/**- * Encrypt the given data using libsodium's secretstream APIs without chunking.- *- * Use {@link decryptBlobBytes} to decrypt the result.- *- * @param data The data to encrypt.- *- * @param key The key to use for encryption.- *- * @returns The encrypted data and the decryption header as {@link Uint8Array}s.- *- * - See: [Note: 3 forms of encryption (Box | Blob | Stream)].- *- * - See: https://doc.libsodium.org/secret-key_cryptography/secretstream- */-export const encryptBlobBytes = async (- data: BytesOrB64,- key: BytesOrB64,-): Promise<EncryptedBlobBytes> => {- await sodium.ready;-- const keyBytes = await bytes(key);- const initPushResult =- sodium.crypto_secretstream_xchacha20poly1305_init_push(keyBytes);- const [pushState, header] = [initPushResult.state, initPushResult.header];-- const pushResult = sodium.crypto_secretstream_xchacha20poly1305_push(- pushState,- await bytes(data),- null,- sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL,- );- return { encryptedData: pushResult, decryptionHeader: header };-};--/**- * A higher level variant of {@link encryptBlobBytes} that returns the both the- * encrypted data and decryption header as base64 strings.- *- * This is the variant expected to serve majority of the public API use cases.- */-export const encryptBlob = async (- data: BytesOrB64,- key: BytesOrB64,-): Promise<EncryptedBlobB64> => {- const { encryptedData, decryptionHeader } = await encryptBlobBytes(- data,- key,- );- return {- encryptedData: await toB64(encryptedData),- decryptionHeader: await toB64(decryptionHeader),- };-};--/**- * Encrypt the provided JSON value (using {@link encryptBlob}) after converting- * it to a JSON string (and UTF-8 encoding it to obtain bytes).- *- * Use {@link decryptMetadataJSON} to decrypt the result and convert it back to- * a JSON value.- */-export const encryptMetadataJSON = (- jsonValue: unknown,- key: BytesOrB64,-): Promise<EncryptedBlobB64> =>- encryptBlob(new TextEncoder().encode(JSON.stringify(jsonValue)), key);--/**- * Encrypt the given data using libsodium's secretstream APIs after breaking it- * into {@link streamEncryptionChunkSize} chunks.- *- * Use {@link decryptStreamBytes} to decrypt the result.- *- * Unlike {@link initChunkDecryption} / {@link encryptFileChunk}, this function- * processes all the chunks at once in a single call to this function.- *- * @param data The data to encrypt.- *- * @returns The encrypted bytes ({@link Uint8Array}) and the decryption header- * (as a base64 string).- *- * - See: [Note: 3 forms of encryption (Box | Blob | Stream)].- *- * - See: https://doc.libsodium.org/secret-key_cryptography/secretstream- */-export const encryptStreamBytes = async (- data: Uint8Array,- key: BytesOrB64,-): Promise<EncryptedFile> => {- await sodium.ready;-- const keyBytes = await bytes(key);- const initPushResult =- sodium.crypto_secretstream_xchacha20poly1305_init_push(keyBytes);- const [pushState, header] = [initPushResult.state, initPushResult.header];- let bytesRead = 0;- let tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;-- const encryptedChunks = [];-- while (tag !== sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL) {- let chunkSize = streamEncryptionChunkSize;- if (bytesRead + chunkSize >= data.length) {- chunkSize = data.length - bytesRead;- tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL;- }-- const buffer = data.slice(bytesRead, bytesRead + chunkSize);- bytesRead += chunkSize;- const pushResult = sodium.crypto_secretstream_xchacha20poly1305_push(- pushState,- buffer,- null,- tag,- );- encryptedChunks.push(pushResult);- }- return {- encryptedData: mergeUint8Arrays(encryptedChunks),- decryptionHeader: await toB64(header),- };-};--/**- * Initialize libsodium's secretstream APIs for encrypting- * {@link streamEncryptionChunkSize} chunks. Subsequently, each chunk can be- * encrypted using {@link encryptStreamChunk}.- *- * Use {@link initChunkDecryption} to initialize the decryption routine, and- * {@link decryptStreamChunk} to decrypt the individual chunks.- *- * See also: {@link encryptStreamBytes} which also does chunked encryption but- * encrypts all the chunks in a single call.- *- * @param key The key to use for encryption.- *- * @returns The decryption header (as a base64 string) which should be preserved- * and used during decryption, and an opaque "push state" that should be passed- * to subsequent calls to {@link encryptStreamChunk} along with the chunks's- * contents.- */-export const initChunkEncryption = async (- key: BytesOrB64,-): Promise<InitChunkEncryptionResult> => {- await sodium.ready;- const keyBytes = await bytes(key);- const { state, header } =- sodium.crypto_secretstream_xchacha20poly1305_init_push(keyBytes);- return { decryptionHeader: await toB64(header), pushState: state };-};--/**- * Encrypt an individual chunk using libsodium's secretstream APIs.- *- * This function is not meant to be standalone, but is instead called in tandem- * with {@link initChunkEncryption} for encrypting data after breaking it into- * chunks.- *- * @param data The chunk's data as bytes ({@link Uint8Array}).- *- * @param pushState The state for this instantiation of chunked encryption. This- * should be treated as opaque libsodium state that should be passed to all- * calls to {@link encryptStreamChunk} that are paired with a particular- * {@link initChunkEncryption}.- *- * @param isFinalChunk `true` if this is the last chunk in the sequence.- *- * @returns The encrypted chunk.- */-export const encryptStreamChunk = async (- data: Uint8Array,- pushState: SodiumStateAddress,- isFinalChunk: boolean,-): Promise<Uint8Array> => {- await sodium.ready;- const tag = isFinalChunk- ? sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL- : sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;- return sodium.crypto_secretstream_xchacha20poly1305_push(- pushState,- data,- null,- tag,- );-};--/**- * Decrypt the result of {@link encryptBox} and return the decrypted bytes.- */-export const decryptBoxBytes = async (- { encryptedData, nonce }: EncryptedBox,- key: BytesOrB64,-): Promise<Uint8Array> => {- await sodium.ready;- return sodium.crypto_secretbox_open_easy(- await bytes(encryptedData),- await bytes(nonce),- await bytes(key),- );-};--/**- * Variant of {@link decryptBoxBytes} that returns the data as a base64 string.- */-export const decryptBox = (- box: EncryptedBox,- key: BytesOrB64,-): Promise<string> => decryptBoxBytes(box, key).then(toB64);--/**- * Decrypt the result of {@link encryptBlobBytes} or {@link encryptBlob}.- */-export const decryptBlobBytes = async (- { encryptedData, decryptionHeader }: EncryptedBlob,- key: BytesOrB64,-): Promise<Uint8Array> => {- await sodium.ready;- const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(- await bytes(decryptionHeader),- await bytes(key),- );- const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(- pullState,- await bytes(encryptedData),- null,- );- return pullResult.message;-};--/**- * A variant of {@link decryptBlobBytes} that returns the result as a base64- * string.- */-export const decryptBlob = (- blob: EncryptedBlob,- key: BytesOrB64,-): Promise<string> => decryptBlobBytes(blob, key).then(toB64);--/**- * Decrypt the result of {@link encryptMetadataJSON} and return the JSON value- * obtained by parsing the decrypted JSON string (which is obtained by UTF-8- * decoding the decrypted bytes).- *- * Since TypeScript doesn't currently have a native JSON type, the returned- * value is casted as an `unknown`.- */-export const decryptMetadataJSON = async (- blob: EncryptedBlob,- key: BytesOrB64,-): Promise<unknown> =>- JSON.parse(- new TextDecoder().decode(await decryptBlobBytes(blob, key)),- ) as unknown;--/**- * Decrypt the result of {@link encryptStreamBytes}.- */-export const decryptStreamBytes = async (- { encryptedData, decryptionHeader }: EncryptedFile,- key: BytesOrB64,-): Promise<Uint8Array> => {- await sodium.ready;- const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(- await fromB64(decryptionHeader),- await bytes(key),- );- const decryptionChunkSize =- streamEncryptionChunkSize +- sodium.crypto_secretstream_xchacha20poly1305_ABYTES;- let bytesRead = 0;- const decryptedChunks = [];- let tag = sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;- while (tag !== sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL) {- let chunkSize = decryptionChunkSize;- if (bytesRead + chunkSize > encryptedData.length) {- chunkSize = encryptedData.length - bytesRead;- }- const buffer = encryptedData.slice(bytesRead, bytesRead + chunkSize);- const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(- pullState,- buffer,- );- decryptedChunks.push(pullResult.message);- tag = pullResult.tag;- bytesRead += chunkSize;- }- return mergeUint8Arrays(decryptedChunks);-};--/**- * Prepare to decrypt the result of {@link initChunkEncryption} and- * {@link encryptStreamChunk}.- *- * @param decryptionHeader The header (as a base64 string) that was produced- * during encryption by {@link initChunkEncryption}.- *- * @param key The encryption key.- *- * @returns The pull state, which should be treated as opaque libsodium specific- * state that should be passed along to each subsequent call to- * {@link decryptStreamChunk}, and the size of each (decrypted) chunk that will- * be produced by subsequent calls to {@link decryptStreamChunk}.- */-export const initChunkDecryption = async (- decryptionHeader: string,- key: BytesOrB64,-): Promise<InitChunkDecryptionResult> => {- await sodium.ready;- const pullState = sodium.crypto_secretstream_xchacha20poly1305_init_pull(- await fromB64(decryptionHeader),- await bytes(key),- );- const decryptionChunkSize =- streamEncryptionChunkSize +- sodium.crypto_secretstream_xchacha20poly1305_ABYTES;- return { pullState, decryptionChunkSize };-};--/**- * Decrypt an individual chunk of the data encrypted using- * {@link initChunkEncryption} and {@link encryptStreamChunk}.- *- * This is meant to be used in tandem with {@link initChunkDecryption}. During- * each invocation, it should be passed the encrypted chunk, and the- * {@link pullState} returned by {@link initChunkDecryption}. It will then- * return the corresponding decrypted chunk's bytes.- */-export const decryptStreamChunk = async (- data: Uint8Array,- pullState: SodiumStateAddress,-): Promise<Uint8Array> => {- await sodium.ready;- const pullResult = sodium.crypto_secretstream_xchacha20poly1305_pull(- pullState,- data,- );- return pullResult.message;-};--/**- * Initialize and return new state that can be used to hash the chunks of data- * in a streaming manner.- *- * [Note: Chunked hashing]- *- * 1. Obtain a hash state using {@link chunkHashInit}.- *- * 2. Pass the hash state and the data chunk to {@link chunkHashUpdate}.- *- * 3. Finalize the hash state and obtain the hash using {@link chunkHashFinal}.- *- * @returns An opaque object representing the hash state. This can be passed- * (along with the data to hash) to {@link chunkHashUpdate}, and the final hash- * obtained using {@link chunkHashFinal}.- */-export const chunkHashInit = async (): Promise<SodiumStateAddress> => {- await sodium.ready;- return sodium.crypto_generichash_init(- null,- sodium.crypto_generichash_BYTES_MAX,- );-};--/**- * Update the hash state to incorporate the contents of the provided data chunk.- *- * See: [Note: Chunked hashing]- *- * @param hashState A hash state obtained using {@link chunkHashInit}.- *- * @param chunk The data (bytes) to hash.- */-export const chunkHashUpdate = async (- hashState: SodiumStateAddress,- chunk: Uint8Array,-) => {- await sodium.ready;- sodium.crypto_generichash_update(hashState, chunk);-};--/**- * Finalize a hash state and return the hash it represents (as a base64 string).- *- * See: [Note: Chunked hashing]- *- * @param hashState A hash state obtained using {@link chunkHashInit} and fed- * chunks using {@link chunkHashUpdate}.- *- * @returns The hash of all the chunks (as a base64 string).- */-export const chunkHashFinal = async (hashState: SodiumStateAddress) => {- await sodium.ready;- const hash = sodium.crypto_generichash_final(- hashState,- sodium.crypto_generichash_BYTES_MAX,- );- return toB64(hash);-};--/**- * Generate a new public/private keypair for use with public-key encryption- * functions, and return their base64 string representations.- *- * These keys are suitable for being used with the {@link boxSeal} and- * {@link boxSealOpen} functions.- */-export const generateKeyPair = async () => {- await sodium.ready;- const keyPair = sodium.crypto_box_keypair();- return {- publicKey: await toB64(keyPair.publicKey),- privateKey: await toB64(keyPair.privateKey),- };-};--/**- * Public key encryption.- *- * Encrypt the given {@link data} using the given {@link publicKey}.- *- * This function performs asymmetric (public-key) encryption. To decrypt the- * result, use {@link boxSealOpen}.- *- * @param data The input data to encrypt, represented as a base64 string.- *- * @param publicKey The public key to use for encryption (as a base64 string).- *- * @returns The encrypted data (as a base64 string).- */-export const boxSeal = async (data: string, publicKey: string) => {- await sodium.ready;- return toB64(- sodium.crypto_box_seal(await fromB64(data), await fromB64(publicKey)),- );-};--/**- * Decrypt the result of {@link boxSeal}.- *- * All parameters are base64 string representations of the underlying data. The- * result is the bytes obtained by decryption.- */-export const boxSealOpenBytes = async (- encryptedData: string,- { publicKey, privateKey }: KeyPair,-): Promise<Uint8Array> => {- await sodium.ready;- return sodium.crypto_box_seal_open(- await fromB64(encryptedData),- await fromB64(publicKey),- await fromB64(privateKey),- );-};--/**- * A variant of {@link boxSealOpenBytes} that returns the result as a base64- * string.- */-export const boxSealOpen = async (encryptedData: string, keyPair: KeyPair) =>- toB64(await boxSealOpenBytes(encryptedData, keyPair));--/**- * Generate a new randomly generated 128-bit salt suitable for use with the key- * derivation functions ({@link deriveKey} and its variants).- *- * @returns The base64 representation of a randomly generated 128-bit salt.- */-export const generateDeriveKeySalt = async () => {- await sodium.ready;- return await toB64(sodium.randombytes_buf(sodium.crypto_pwhash_SALTBYTES));-};--/**- * Derive a key by hashing the given {@link passphrase} using Argon 2id.- *- * While the underlying primitive is a password hash (e.g for its storage), this- * function is also meant for key derivation using a low-entropy input by- * deriving a longer hash from the user's human chosen passphrase.- *- * The returned key can be used with the various *Box encryption routines.- *- * @param passphrase The password / passphrase to hash (normal UTF-8 string).- *- * @param salt Base64 string representing the salt to use when hashing.- *- * @param opsLimit Operation limit. The maximum amount of computations to- * perform.- *- * @param memLimit Memory limit. The maximum amount of RAM to use.- *- * @returns The base64 representation of a 256-bit key suitable for being used- * with libsodium's secretbox APIs.- */-export const deriveKey = async (- passphrase: string,- salt: string,- opsLimit: number,- memLimit: number,-) => {- await sodium.ready;- return await toB64(- sodium.crypto_pwhash(- sodium.crypto_secretbox_KEYBYTES,- sodium.from_string(passphrase),- await fromB64(salt),- opsLimit,- memLimit,- sodium.crypto_pwhash_ALG_ARGON2ID13,- ),- );-};--/**- * A variant of {@link deriveKey} with (dynamic) parameters for deriving- * sensitive keys (like the user's master key KEK (key encryption key).- *- * This function defers to {@link deriveKey} after choosing the most secure ops- * and mem limits that the current device can handle. For details about these- * limits, see https://libsodium.gitbook.io/doc/password_hashing/default_phf.- *- * @returns Both the derived key, and the ops and mem limits that were chosen- * during the derivation (this information will be needed the user's other- * clients to derive the same result).- */-export const deriveSensitiveKey = async (- passphrase: string,-): Promise<DerivedKey> => {- await sodium.ready;-- const salt = await generateDeriveKeySalt();-- const desiredStrength =- sodium.crypto_pwhash_MEMLIMIT_SENSITIVE *- sodium.crypto_pwhash_OPSLIMIT_SENSITIVE;- // When the sensitive memLimit (1 GB) is used, on low spec devices the OS- // often kills the app with OOM. Note that could happen at a later stage- // too, so checking the current device's capabilities will not help. For- // example, the user may create an account on a powerful desktop device, but- // then try to log in later on their weaker mobile device, and will need to- // reset their password.- //- // To avoid this, we start with the moderate memLimit (256 MB), but scale up- // the opsLimit correspondingly (16). This ensures that the product of these- // two variables (the area under the graph that determines the amount of- // work) stays the same.- let memLimit = sodium.crypto_pwhash_MEMLIMIT_MODERATE; // = 256 MB- const factor = Math.floor(- sodium.crypto_pwhash_MEMLIMIT_SENSITIVE /- sodium.crypto_pwhash_MEMLIMIT_MODERATE,- ); // = 4- let opsLimit = sodium.crypto_pwhash_OPSLIMIT_SENSITIVE * factor; // = 16- if (memLimit * opsLimit != desiredStrength) {- throw new Error(`Invalid mem and ops limits: ${memLimit}, ${opsLimit}`);- }-- const minMemLimit = sodium.crypto_pwhash_MEMLIMIT_MIN;- while (memLimit > minMemLimit) {- try {- const key = await deriveKey(passphrase, salt, opsLimit, memLimit);- return { key, salt, opsLimit, memLimit };- } catch {- opsLimit *= 2;- memLimit /= 2;- }- }- throw new Error(deriveKeyInsufficientMemoryErrorMessage);-};--/**- * A variant of {@link deriveSensitiveKey} for deriving an alternative key with- * parameters suitable for interactive use.- */-export const deriveInteractiveKey = async (- passphrase: string,-): Promise<DerivedKey> => {- const salt = await generateDeriveKeySalt();- const opsLimit = sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE;- const memLimit = sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE;-- const key = await deriveKey(passphrase, salt, opsLimit, memLimit);- return { key, salt, opsLimit, memLimit };-};--/**- * Derive a {@link subKeyID}-th subkey of length {@link subKeyLength} bytes by- * applying a KDF (Key Derivation Function) for the given {@link key} and the- * {@link context}.- *- * Multiple secret subkeys can be (deterministically) derived from a single- * high-entropy key. Knowledge of the derived key does not impact the security- * of the key from which it was derived, or of its potential sibling subkeys.- *- * See: https://doc.libsodium.org/key_derivation- *- * @param key The key whose subkey we are deriving. In the context of- * key derivation, this is usually referred to as the "master key", but we- * deemphasize that nomenclature to avoid confusion with the user's master key.- *- * @param subKeyLength The length of the required subkey.- *- * @param subKeyID An identifier of the subkey.- *- * @param context A short but otherwise arbitrary string (non-secret) used to- * separate domains in which the subkeys are going to be used.- *- * @returns The bytes of the subkey.- *- * Note that returning bytes is a bit unusual, usually we'd return the base64- * string from functions. However, this particular function is used in only one- * place in our code, and so we adapt the interface for its convenience.- */-export const deriveSubKeyBytes = async (- key: BytesOrB64,- subKeyLength: number,- subKeyID: number,- context: string,-): Promise<Uint8Array> => {- await sodium.ready;- return sodium.crypto_kdf_derive_from_key(- subKeyLength,- subKeyID,- context,- await bytes(key),- );-};diff --git a/web/apps/albums/vendor/ente-base/crypto/types.ts b/web/apps/albums/vendor/ente-base/crypto/types.tsdeleted file mode 100644index 8b82a2aef8..0000000000--- a/web/apps/albums/vendor/ente-base/crypto/types.ts+++ /dev/null@@ -1,243 +0,0 @@-/**- * @file types shared between the public API (main thread) and implementation- * (worker thread). Also some constants, but no code.- */-import { type StateAddress } from "libsodium-wrappers-sumo";--/**- * An opaque object meant to be threaded through various functions that deal- * with resumable chunk based processing.- */-export type SodiumStateAddress = StateAddress;--/**- * The various *Stream encryption functions break up the input into chunks of- * {@link streamEncryptionChunkSize} bytes during encryption (except the last- * chunk which can be smaller since a file would rarely align exactly to a- * {@link streamEncryptionChunkSize} multiple).- *- * The various *Stream decryption functions also assume that each potential- * chunk is {@link streamEncryptionChunkSize} long.- *- * This value of this constant is 4 MB (and is unlikely to change).- */-export const streamEncryptionChunkSize = 4 * 1024 * 1024;--/**- * The message of the {@link Error} that is thrown by {@link deriveSensitiveKey}- * if we could not find acceptable ops and mem limit combinations without- * exceeded the maximum mem limit.- *- * Generally, this indicates that the current device is not powerful enough to- * perform the key derivation. This is rare for computers, but can happen with- * older mobile devices with too little RAM.- */-export const deriveKeyInsufficientMemoryErrorMessage =- "Failed to derive key (insufficient memory)";--/**- * Data provided either as bytes ({@link Uint8Array}) or their base64 string- * representation.- */-export type BytesOrB64 = Uint8Array | string;--/**- * The result of encryption using the secretbox APIs.- *- * It contains an encrypted data and a randomly generated nonce that was used- * during encryption. Both these values are needed to decrypt the data. The- * nonce does not need to be secret.- *- * See: [Note: 3 forms of encryption (Box | Blob | Stream)].- */-export interface EncryptedBox {- /**- * The data to decrypt.- */- encryptedData: BytesOrB64;- /**- * The nonce that was used during encryption.- *- * The nonce is required to decrypt the data, but it does not need to be- * kept secret.- */- nonce: BytesOrB64;-}--export interface EncryptedBoxB64 {- /**- * The encrypted data as a base64 string.- */- encryptedData: string;- /**- * The nonce that was used during encryption, as a base64 string.- *- * The nonce is required to decrypt the data, but it does not need to be- * kept secret.- */- nonce: string;-}--/**- * The result of encryption using the secretstream APIs without chunking.- *- * It contains an encrypted data and a header that should be provided during- * decryption. The header does not need to be secret.- *- * See: [Note: 3 forms of encryption (Box | Blob | Stream)].- *- * This type is a combination of {@link EncryptedBlobBytes} and- * {@link EncryptedBlobB64} which allows the decryption routines to accept- * either the bytes or the base64 variants produced by the encryption routines.- */-export interface EncryptedBlob {- /**- * The encrypted data.- */- encryptedData: BytesOrB64;- /**- * The decryption header.- *- * While the exact contents of the header are libsodium's internal details,- * it effectively contains a random nonce generated by libsodium. It does- * not need to be secret, but it is required to decrypt the data.- */- decryptionHeader: BytesOrB64;-}--/**- * A variant of {@link EncryptedBlob} that has the encrypted data and header- * as bytes ({@link Uint8Array}s).- */-export interface EncryptedBlobBytes {- /**- * The encrypted data.- */- encryptedData: Uint8Array;- /**- * The decryption header.- *- * While the exact contents of the header are libsodium's internal details,- * it effectively contains a random nonce generated by libsodium. It does- * not need to be secret, but it is required to decrypt the data.- */- decryptionHeader: Uint8Array;-}--/**- * A variant of {@link EncryptedBlob} that has the encrypted data and header- * as base64 strings.- */-export interface EncryptedBlobB64 {- /**- * The encrypted data as a base64 string.- */- encryptedData: string;- /**- * A base64 string containing the decryption header.- *- * While the exact contents of the header are libsodium's internal details,- * it effectively contains a random nonce generated by libsodium. It does- * not need to be secret, but it is required to decrypt the data.- */- decryptionHeader: string;-}--/**- * An intermediate between {@link EncryptedBlobBytes} and- * {@link EncryptedBlobB64} that has the encrypted as bytes- * ({@link Uint8Array}s), but the {@link decryptionHeader} as a base64 string.- *- * Such a format is handy for encrypting files, since it can then directly be- * used (the file's encrypted bytes get uploaded separately, whilst the base64- * decryption header becomes part of the corresponding {@link EnteFile}).- */-export interface EncryptedFile {- /**- * The encrypted data.- */- encryptedData: Uint8Array;- /**- * A base64 string containing the decryption header.- *- * While the exact contents of the header are libsodium's internal details,- * it effectively contains a random nonce generated by libsodium. It does- * not need to be secret, but it is required to decrypt the data.- */- decryptionHeader: string;-}--/**- * An object returned by the init function of chunked encryption routines.- */-export interface InitChunkEncryptionResult {- /**- * A base64 string containing the decryption header.- *- * While the exact contents of the header are libsodium's internal details,- * it effectively contains a random nonce generated by libsodium. It does- * not need to be secret, but it is required to decrypt the data.- */- decryptionHeader: string;- /**- * An opaque value that refers to the internal state used by the resumable- * calls in the encryption sequence.- */- pushState: SodiumStateAddress;-}--/**- * An object returned by the init function of chunked decryption routines.- */-export interface InitChunkDecryptionResult {- /**- * An opaque value that refers to the internal state used by the resumable- * calls in the decryption sequence.- */- pullState: SodiumStateAddress;- /**- * The expected size of each chunk.- */- decryptionChunkSize: number;-}--/**- * A pair of public and private keys.- */-export interface KeyPair {- /**- * The public key of the keypair, as a base64 encoded string.- */- publicKey: string;- /**- * The private key of the keypair, as a base64 encoded string.- *- * Some places also refer to it as the "secret key".- *- * See: [Note: privateKey and secretKey].- */- privateKey: string;-}--/**- * A key derived from a user provided passphrase, and the various attributes- * that were used during the key derivation.- */-export interface DerivedKey {- /**- * The newly derived key itself, as a base64 encoded string.- */- key: string;- /**- * The randomly generated salt (as a base64 string) that was used when deriving the key.- */- salt: string;- /**- * opsLimit used during key derivation.- */- opsLimit: number;- /**- * memLimit used during key derivation.- * */- memLimit: number;-}diff --git a/web/apps/albums/vendor/ente-base/crypto/worker.ts b/web/apps/albums/vendor/ente-base/crypto/worker.tsdeleted file mode 100644index bc25a7c0ad..0000000000--- a/web/apps/albums/vendor/ente-base/crypto/worker.ts+++ /dev/null@@ -1,53 +0,0 @@-import { expose } from "comlink";-import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";-import * as libsodium from "./libsodium";--/**- * A web worker that exposes the functions defined by libsodium.ts.- *- * See: [Note: Crypto code hierarchy].- *- * Note: Keep these methods logic free. They are meant to be trivial proxies.- */-export class CryptoWorker {- toB64 = libsodium.toB64;- fromB64 = libsodium.fromB64;- toB64URLSafe = libsodium.toB64URLSafe;- toB64URLSafeNoPadding = libsodium.toB64URLSafeNoPadding;- fromB64URLSafeNoPadding = libsodium.fromB64URLSafeNoPadding;- toHex = libsodium.toHex;- fromHex = libsodium.fromHex;- generateKey = libsodium.generateKey;- generateBlobOrStreamKey = libsodium.generateBlobOrStreamKey;- encryptBox = libsodium.encryptBox;- encryptBlob = libsodium.encryptBlob;- encryptBlobBytes = libsodium.encryptBlobBytes;- encryptMetadataJSON = libsodium.encryptMetadataJSON;- encryptStreamBytes = libsodium.encryptStreamBytes;- initChunkEncryption = libsodium.initChunkEncryption;- encryptStreamChunk = libsodium.encryptStreamChunk;- decryptBox = libsodium.decryptBox;- decryptBoxBytes = libsodium.decryptBoxBytes;- decryptBlob = libsodium.decryptBlob;- decryptBlobBytes = libsodium.decryptBlobBytes;- decryptMetadataJSON = libsodium.decryptMetadataJSON;- decryptStreamBytes = libsodium.decryptStreamBytes;- initChunkDecryption = libsodium.initChunkDecryption;- decryptStreamChunk = libsodium.decryptStreamChunk;- chunkHashInit = libsodium.chunkHashInit;- chunkHashUpdate = libsodium.chunkHashUpdate;- chunkHashFinal = libsodium.chunkHashFinal;- generateKeyPair = libsodium.generateKeyPair;- boxSeal = libsodium.boxSeal;- boxSealOpen = libsodium.boxSealOpen;- boxSealOpenBytes = libsodium.boxSealOpenBytes;- generateDeriveKeySalt = libsodium.generateDeriveKeySalt;- deriveKey = libsodium.deriveKey;- deriveSensitiveKey = libsodium.deriveSensitiveKey;- deriveInteractiveKey = libsodium.deriveInteractiveKey;- deriveSubKeyBytes = libsodium.deriveSubKeyBytes;-}--expose(CryptoWorker);--logUnhandledErrorsAndRejectionsInWorker();diff --git a/web/apps/albums/vendor/ente-base/date.ts b/web/apps/albums/vendor/ente-base/date.tsdeleted file mode 100644index 1aea5aa2b1..0000000000--- a/web/apps/albums/vendor/ente-base/date.ts+++ /dev/null@@ -1,7 +0,0 @@-/**- * Return `true` if both the given dates have the same day.- */-export const isSameDay = (first: Date, second: Date) =>- first.getFullYear() === second.getFullYear() &&- first.getMonth() === second.getMonth() &&- first.getDate() === second.getDate();diff --git a/web/apps/albums/vendor/ente-base/env.ts b/web/apps/albums/vendor/ente-base/env.tsdeleted file mode 100644index 1164164ba6..0000000000--- a/web/apps/albums/vendor/ente-base/env.ts+++ /dev/null@@ -1,37 +0,0 @@-/**- * A build is considered as a development build if either the NODE_ENV is- * environment variable is set to 'development'.- *- * NODE_ENV is automatically set to 'development' when we run `yarn dev`. From- * Next.js docs:- *- * > If the environment variable NODE_ENV is unassigned, Next.js automatically- * assigns development when running the `next dev` command, or production for- * all other commands.- */-export const isDevBuild = process.env.NODE_ENV == "development";--/**- * `true` if we're running in the default global context (aka the main thread)- * of a web browser.- *- * In particular, this is `false` when we're running in a web worker,- * irrespective of whether the worker is running in a Node.js context or a web- * browser context.- *- * > We can be running in a browser context either if the user has the page open- * in a web browser, or if we're the renderer process of an Electron app.- *- * Note that this cannot be a constant, otherwise it'll get inlined during SSR- * with the wrong value.- */-export const haveWindow = () => typeof window != "undefined";--/**- * Return true if we are running in a [Web- * Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)- *- * Note that this cannot be a constant, otherwise it'll get inlined during SSR- * with the wrong value.- */-export const inWorker = () => typeof importScripts == "function";diff --git a/web/apps/albums/vendor/ente-base/file-name.ts b/web/apps/albums/vendor/ente-base/file-name.tsdeleted file mode 100644index 4b679d5a24..0000000000--- a/web/apps/albums/vendor/ente-base/file-name.ts+++ /dev/null@@ -1,105 +0,0 @@-/**- * The two parts of a file name - the name itself, and an (optional) extension.- *- * The extension does not include the dot.- */-type FileNameComponents = [name: string, extension: string | undefined];--/**- * Split a filename into its components - the name itself, and the extension (if- * any) - returning both. The dot is not included in either.- *- * For example, `foo-bar.png` will be split into ["foo-bar", "png"].- *- * See {@link fileNameFromComponents} for the inverse operation.- */-export const nameAndExtension = (fileName: string): FileNameComponents => {- const i = fileName.lastIndexOf(".");- // No extension- if (i == -1) return [fileName, undefined];- // A hidden file without an extension, e.g. ".gitignore"- if (i == 0) return [fileName, undefined];- // Both components present, just omit the dot.- return [fileName.slice(0, i), fileName.slice(i + 1)];-};--/**- * If the file name or path has an extension, return a lowercased version of it.- *- * This is handy when comparing the extension to a known set without worrying- * about case sensitivity.- *- * See {@link nameAndExtension} for its more generic sibling.- */-export const lowercaseExtension = (- fileNameOrPath: string,-): string | undefined => {- // We rely on the implementation of nameAndExtension using lastIndexOf to- // allow us to also work on paths.- const [, ext] = nameAndExtension(fileNameOrPath);- return ext?.toLowerCase();-};--/**- * Construct a file name from its components (name and extension).- *- * Inverse of {@link nameAndExtension}.- */-export const fileNameFromComponents = (components: FileNameComponents) =>- components.filter((x) => !!x).join(".");--/**- * Return the file name portion from the given {@link path}.- *- * This tries to emulate the UNIX `basename` command. In particular, any- * trailing slashes on the path are trimmed, so this function can be used to get- * the name of the directory too.- *- * The path is assumed to use POSIX separators ("/").- */-export const basename = (path: string) => {- const pathComponents = path.split("/");- for (let i = pathComponents.length - 1; i >= 0; i--) {- const component = pathComponents[i];- if (component && component.length > 0) return component;- }- return path;-};--/**- * Return the directory portion from the given {@link path}.- *- * This tries to emulate the UNIX `dirname` command. In particular, any trailing- * slashes on the path are trimmed, so this function can be used to get the path- * leading up to a directory too.- *- * The path is assumed to use POSIX separators ("/").- */-export const dirname = (path: string) => {- const pathComponents = path.split("/");- while (pathComponents.pop() == "") {- /* no-op */- }- return pathComponents.join("/");-};--/**- * Return a new path by joining two path components using the POSIX path- * separator ("/").- *- * This is usually a trivial `p1/p2`, however it also handles the case where p1- * already ends with a trailing slash. This can happen even if p1 is obtained- * from a place which guarantees that only directory paths will be returned,- * because p1 can be the path to a root folder (e.g. "/" on Linux, or "C:/" on- * Windows), and the trivial join would then result in double slashes.- *- * @param p1 A path component that is expected to be using POSIX path- * separators.- *- * @param p2 A path component that is expected to be using POSIX path- * separators.- *- * @returns A path by joining p1 and p2 with a POSIX path separator if needed.- */-export const joinPath = (p1: string, p2: string) =>- p1.endsWith("/") ? p1 + p2 : `${p1}/${p2}`;diff --git a/web/apps/albums/vendor/ente-base/http.ts b/web/apps/albums/vendor/ente-base/http.tsdeleted file mode 100644index 6d8489689b..0000000000--- a/web/apps/albums/vendor/ente-base/http.ts+++ /dev/null@@ -1,311 +0,0 @@-import { wait } from "ente-utils/promise";-import { z } from "zod";-import { clientPackageName } from "./app";-import log from "./log";-import { ensureAuthToken } from "./token";--/**- * Return headers that should be passed alongwith (almost) all authenticated- * `fetch` calls that we make to our API servers.- *- * - The auth token- * - The client package name.- */-export const authenticatedRequestHeaders = async () => ({- "X-Auth-Token": await ensureAuthToken(),- "X-Client-Package": clientPackageName,-});--/**- * Return headers that should be passed alongwith (almost) all unauthenticated- * `fetch` calls that we make to our remotes like our API servers (museum), or- * to pre-signed URLs that are handled by the S3 storage buckets themselves.- *- * - The client package name.- */-export const publicRequestHeaders = () => ({- "X-Client-Package": clientPackageName,-});--/**- * A set of credentials needed to make public collections related API requests.- */-export interface PublicAlbumsCredentials {- /**- * [Note: Public album access token]- *- * The public album access is a token that serves a similar purpose as the- * "X-Auth-Token" for usual authenticated API requests that happen for a- * logged in user, except:- *- * - It will be passed as the "X-Auth-Access-Token" header, and- * - It also tells remote about the public album under consideration.- *- * This access token is variously referred to as the album token, or the- * auth token, when the context is clear. The client obtains this from the- * "t" query parameter of a public album URL, and then uses it both to:- *- * 1. Identify and authenticate itself with remote (this header).- *- * 2. Scope local storage per public album by using this access token as a- * part of the local storage key. In this context it is sometimes also- * referred to as a "collectionUID" by old code.- */- accessToken: string;- /**- * [Note: Password token for public albums requests].- *- * A password protected access token. This is only needed for albums that- * are behind a password. In such cases, the client needs to fetch this- * extra token from remote (in exchange for the public album's password),- * and then pass it as the "X-Auth-Access-Token-JWT" header in authenticated- * public collections related API requests.- */- accessTokenJWT?: string | undefined;-}--/**- * Return headers that should be passed alongwith public collection related- * authenticated `fetch` calls that we make to our API servers.- *- * - The auth token.- * - The password protected auth token (if provided).- * - The client package name.- */-export const authenticatedPublicAlbumsRequestHeaders = ({- accessToken,- accessTokenJWT,-}: PublicAlbumsCredentials) => ({- "X-Auth-Access-Token": accessToken,- ...(accessTokenJWT && { "X-Auth-Access-Token-JWT": accessTokenJWT }),- "X-Client-Package": clientPackageName,-});--/**- * A custom Error that is thrown if a fetch fails with a non-2xx HTTP status.- */-export class HTTPError extends Error {- res: Response;- details: Record<string, string>;-- constructor(res: Response) {- // Trim off any query parameters from the URL before logging, it may- // have tokens.- //- // Nb: res.url is URL obtained after any redirects, and thus is not- // necessarily the same as the request's URL.- const url = new URL(res.url);- url.search = "";- super(`HTTP ${res.status} ${res.statusText} (${url.pathname})`);-- const requestID = res.headers.get("x-request-id");- const details = { url: url.href, ...(requestID && { requestID }) };-- // Cargo culted from- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#custom_error_types- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition- if (Error.captureStackTrace) Error.captureStackTrace(this, HTTPError);-- this.name = this.constructor.name;- this.res = res;- this.details = details;- }-}--/**- * A convenience method that throws an {@link HTTPError} if the given- * {@link Response} does not have a HTTP 2xx status.- */-export const ensureOk = (res: Response) => {- if (!res.ok) {- const e = new HTTPError(res);- log.error(`${e.message} ${JSON.stringify(e.details)}`);- throw e;- }-};--/**- * Return true if this is a HTTP error with the given {@link httpStatus}.- */-export const isHTTPErrorWithStatus = (e: unknown, httpStatus: number) =>- e instanceof HTTPError && e.res.status == httpStatus;--/**- * Return true if this is a HTTP "client" error.- *- * This is a convenience matcher to check if {@link e} is an instance of- * {@link HTTPError} with a 4xx status code. Such errors are client errors, and- * (generally) retrying them will not help.- */-export const isHTTP4xxError = (e: unknown) =>- e instanceof HTTPError && e.res.status >= 400 && e.res.status <= 499;--/**- * Return true if this is a HTTP 401 error.- *- * For authenticated requests, an HTTP "401 Unauthorized" indicates that the- * credentials (auth token) is not valid.- */-export const isHTTP401Error = (e: unknown) =>- e instanceof HTTPError && e.res.status == 401;--/**- * Return `true` if this is an error because of a HTTP failure response returned- * by museum with the given "code" and HTTP status.- *- * > The function is async because it needs to parse the payload.- *- * For some known set of errors, museum returns a payload of the form- *- * {"code":"USER_NOT_REGISTERED","message":"User is not registered"}- *- * where the code can be used to match a specific reason for the HTTP request- * failing. This function can be used as a predicate to check both the HTTP- * status code and the "code" within the payload.- */-export const isMuseumHTTPError = async (- e: unknown,- httpStatus: number,- code: string,-) => {- if (e instanceof HTTPError && e.res.status == httpStatus) {- try {- const payload = z- .object({ code: z.string() })- .parse(await e.res.json());- return payload.code == code;- } catch (e) {- log.warn("Ignoring error when parsing error payload", e);- return false;- }- }- return false;-};--interface RetryAsyncOperationOpts {- /**- * An optional modification to the default wait times between retries.- *- * - default 1 orig + 3 retries (2s, 5s, 10s)- * - "background" 1 orig + 3 retries (5s, 25s, 120s)- *- * default is fine for most operations, including interactive ones where we- * don't want to wait too long before giving up. "background" is suitable- * for non-interactive operations where we can wait for longer (thus better- * handle remote hiccups) without degrading the user's experience.- */- retryProfile?: "background";- /**- * An optional function that is called with the corresponding error whenever- * {@link op} rejects. It should throw the error if the retries should- * immediately be aborted.- */- abortIfNeeded?: (error: unknown) => void;-}--/**- * Retry a async operation on failure up to 4 times (1 original + 3 retries)- * with exponential backoff.- *- * [Note: Retries of network requests should be idempotent]- *- * When dealing with network requests, avoid using this function directly, use- * one of its wrappers like {@link retryEnsuringHTTPOk} instead. Those wrappers- * ultimately use this function only, and there is nothing wrong with this- * function generally, however since this function allows retrying arbitrary- * promises, it is easy accidentally try and attempt retries of non-idemponent- * requests, while the more restricted API of {@link retryEnsuringHTTPOk} and- * other {@link HTTPRequestRetrier}s makes such misuse less likely.- *- * @param op A function that performs the operation, returning the promise for- * its completion.- *- * @param opts Optional tweaks to the default implementation. See- * {@link RetryAsyncOperationOpts}.- *- * @returns A promise that fulfills with to the result of a first successfully- * fulfilled promise of the 4 (1 + 3) attempts, or rejects with the error- * obtained either when {@link abortIfNeeded} throws, or with the error from the- * last attempt otherwise.- */-export const retryAsyncOperation = async <T>(- op: () => Promise<T>,- opts?: RetryAsyncOperationOpts,-): Promise<T> => {- const { retryProfile, abortIfNeeded } = opts ?? {};- const waitTimeBeforeNextTry =- retryProfile == "background"- ? [10000, 30000, 120000]- : [2000, 5000, 10000];-- while (true) {- try {- return await op();- } catch (e) {- if (abortIfNeeded) {- abortIfNeeded(e);- }- const t = waitTimeBeforeNextTry.shift();- if (!t) throw e;- log.warn("Will retry potentially transient request failure", e);- await wait(t);- }- }-};--/**- * A function that wraps the request(s) in retries if needed.- *- * See {@link retryEnsuringHTTPOk} for the canonical example. This typedef is to- * allow us to talk about and pass functions that behave similar to- * {@link retryEnsuringHTTPOk}, but perhaps with other additional checks.- *- * See also: [Note: Retries of network requests should be idempotent]- */-export type HTTPRequestRetrier = (- request: () => Promise<Response>,- opts?: HTTPRequestRetrierOpts,-) => Promise<Response>;--type HTTPRequestRetrierOpts = Pick<RetryAsyncOperationOpts, "retryProfile">;--/**- * A helper function to adapt {@link retryAsyncOperation} for HTTP fetches.- *- * This extends {@link retryAsyncOperation} by treating any non-200 OK status- * (as matched by {@link ensureOk}) as an error that should be retried.- */-export const retryEnsuringHTTPOk: HTTPRequestRetrier = (- request: () => Promise<Response>,- opts?: HTTPRequestRetrierOpts,-) =>- retryAsyncOperation(async () => {- const r = await request();- ensureOk(r);- return r;- }, opts);--/**- * A helper function to adapt {@link retryAsyncOperation} for HTTP fetches, but- * treating any 4xx HTTP responses as irrecoverable failures.- *- * This is similar to {@link retryEnsuringHTTPOk}, except it stops retrying if- * remote responds with a 4xx HTTP status.- */-export const retryEnsuringHTTPOkOr4xx: HTTPRequestRetrier = (- request: () => Promise<Response>,- opts?: HTTPRequestRetrierOpts,-) =>- retryAsyncOperation(- async () => {- const r = await request();- ensureOk(r);- return r;- },- {- ...opts,- abortIfNeeded(e) {- if (isHTTP4xxError(e)) throw e;- },- },- );diff --git a/web/apps/albums/vendor/ente-base/i18n-date.ts b/web/apps/albums/vendor/ente-base/i18n-date.tsdeleted file mode 100644index 05cc4fd8af..0000000000--- a/web/apps/albums/vendor/ente-base/i18n-date.ts+++ /dev/null@@ -1,121 +0,0 @@-/**- * @file Various date formatters.- *- * Note that we rely on the current behaviour of a full reload on changing the- * language. See: [Note: Changing locale causes a full reload].- */-import i18n, { t } from "i18next";--const _dateFormat = new Intl.DateTimeFormat(i18n.language, {- weekday: "short",- day: "numeric",- month: "short",- year: "numeric",-});--const _dateWithoutYearFormat = new Intl.DateTimeFormat(i18n.language, {- weekday: "short",- day: "numeric",- month: "short",-});--const _timeFormat = new Intl.DateTimeFormat(i18n.language, {- timeStyle: "short",-});--/**- * Return a locale aware formatted date from the given {@link Date}.- *- * The behaviour depends upon whether the given {@link date} falls within the- * current calendar year.- *- * - For dates in the current year, year is omitted, e.g, "Fri, 21 Feb".- *- * - Otherwise, the year is included, e.g., "Fri, 21 Feb 2025".- */-export const formattedDate = (date: Date) =>- (isSameYear(date) ? _dateWithoutYearFormat : _dateFormat).format(date);--const isSameYear = (date: Date) =>- new Date().getFullYear() === date.getFullYear();--/**- * Return a locale aware formatted time from the given {@link Date}.- *- * Example: "11:51 AM"- */-export const formattedTime = (date: Date) => _timeFormat.format(date);--/**- * Return a locale aware formatted date and time from the given {@link Date},- * using the year omission behavior as documented in {@link formattedDate}.- *- * Example:- * - If within year: "Fri, 21 Feb at 11:51 AM".- * - Otherwise: "Fri, 21 Feb 2025 at 11:51 AM"- *- * @param dateOrEpochMicroseconds A JavaScript Date or a numeric epoch- * microseconds value.- *- * [Note: Remote timestamps are epoch microseconds]- *- * Remote talks in terms of epoch microseconds, while JavaScript dates are- * underlain by epoch milliseconds.- *- * As a convenience, this function can be either be directly passed a JavaScript- * date, or it can be given the raw epoch microseconds value and it'll convert- * internally.- */-export const formattedDateTime = (dateOrEpochMicroseconds: Date | number) =>- _formattedDateTime(toDate(dateOrEpochMicroseconds));--const _formattedDateTime = (date: Date) =>- [formattedDate(date), t("at"), formattedTime(date)].join(" ");--const toDate = (dm: Date | number) =>- typeof dm == "number" ? new Date(dm / 1000) : dm;--let _relativeTimeFormat: Intl.RelativeTimeFormat | undefined;--/**- * Return a locale aware relative version of the given date.- *- * Example: "in 23 days"- *- * @param dateOrEpochMicroseconds A JavaScript Date or a numeric epoch- * microseconds value.- *- * See: [Note: Remote timestamps are epoch microseconds]- */-export const formattedDateRelative = (- dateOrEpochMicroseconds: Date | number,-) => {- const units: [Intl.RelativeTimeFormatUnit, number][] = [- ["year", 24 * 60 * 60 * 1000 * 365],- ["month", (24 * 60 * 60 * 1000 * 365) / 12],- ["day", 24 * 60 * 60 * 1000],- ["hour", 60 * 60 * 1000],- ["minute", 60 * 1000],- ["second", 1000],- ];-- const date = toDate(dateOrEpochMicroseconds);-- // Math.abs accounts for both past and future scenarios.- const elapsed = Math.abs(date.getTime() - Date.now());-- // Lazily created, then cached, instance of RelativeTimeFormat.- const relativeTimeFormat = (_relativeTimeFormat ??=- new Intl.RelativeTimeFormat(i18n.language, {- localeMatcher: "best fit",- numeric: "always",- style: "short",- }));-- for (const [u, d] of units) {- if (elapsed > d)- return relativeTimeFormat.format(Math.round(elapsed / d), u);- }-- return relativeTimeFormat.format(Math.round(elapsed / 1000), "second");-};diff --git a/web/apps/albums/vendor/ente-base/i18n.ts b/web/apps/albums/vendor/ente-base/i18n.tsdeleted file mode 100644index 7e99885473..0000000000--- a/web/apps/albums/vendor/ente-base/i18n.ts+++ /dev/null@@ -1,339 +0,0 @@-import { isDevBuild } from "ente-base/env";-import log from "ente-base/log";-import { includes } from "ente-utils/type-guards";-import { getUserLocales } from "get-user-locale";-import i18n from "i18next";-import resourcesToBackend from "i18next-resources-to-backend";-import { initReactI18next } from "react-i18next";-import enUSTranslation from "../../../../packages/base/locales/en-US/translation.json";--/**- * List of all {@link SupportedLocale}s.- *- * Locales are combinations of a language code, and an optional region code.- *- * For example, "en", "en-US", "en-IN" (Indian English), "pt" (Portuguese),- * "pt-BR" (Brazilian Portuguese).- *- * In our Crowdin Project, we have work-in-progress translations into more- * languages than this. When a translation reaches a high enough coverage, say- * 90%, then we manually add it to this list of supported languages.- */-export const supportedLocales = [- "en-US" /* English */,- "fr-FR" /* French */,- "de-DE" /* German */,- "ca-ES" /* Catalan */,- "zh-CN" /* Simplified Chinese */,- "nl-NL" /* Dutch */,- "es-ES" /* Spanish */,- "pt-PT" /* Portuguese */,- "pt-BR" /* Portuguese, Brazilian */,- "ru-RU" /* Russian */,- "pl-PL" /* Polish */,- "it-IT" /* Italian */,- "lt-LT" /* Lithuanian */,- "uk-UA" /* Ukrainian */,- "vi-VN" /* Vietnamese */,- "ja-JP" /* Japanese */,- "ar-SA" /* Arabic */,- "tr-TR" /* Turkish */,- "cs-CZ" /* Czech */,- "el-GR" /* Greek */,-] as const;--/** The type of {@link supportedLocales}. */-export type SupportedLocale = (typeof supportedLocales)[number];--const defaultLocale: SupportedLocale = "en-US";-const defaultNamespace = "translation";--/**- * Load translations and add custom formatters.- *- * Localization and related concerns (aka "internationalization", or "i18n") for- * our apps is handled by i18n framework.- *- * In addition to the base i18next package, we use two of its plugins:- *- * - i18next-http-backend, for loading the JSON files containing the translations- * at runtime, and- *- * - react-i18next, which adds React specific APIs- *- * This function also adds our custom formatters. They can be used within the- * translated strings by using `{{val, formatterName}}`. For more details, see- * https://www.i18next.com/translation-function/formatting.- *- * Our custom formatters:- *- * - "date": Formats an epoch microsecond value into a string containing the- * year, month and day of the the date. For example, under "en-US" it'll- * produce a string like "July 19, 2024".- */-export const setupI18n = async () => {- const localeString = localStorage.getItem("locale") ?? undefined;- const locale = closestSupportedLocale(localeString);-- // https://www.i18next.com/overview/api- await i18n- // i18next-resources-to-backend: Use webpack to bundle translation, but- // still fetch them lazily using a dynamic import.- //- // The benefit of this is that, unlike the http backend that uses files- // from the public folder, these JSON files are content hash named and- // eminently cacheable.- //- // Inline the default locale to avoid blocking first render on an extra- // locale chunk fetch for the most common startup path.- //- // https://github.com/i18next/i18next-resources-to-backend- .use(- resourcesToBackend(- (language: string, namespace: string) => {- if (- language === defaultLocale &&- namespace === defaultNamespace- ) {- return enUSTranslation;- }-- return import(- `../../../../packages/base/locales/${language}/${namespace}.json`- );- },- ),- )- // react-i18next: React support- // Pass the i18n instance to react-i18next.- .use(initReactI18next)- // Initialize i18next- // Option docs: https://www.i18next.com/overview/configuration-options- .init({- debug: isDevBuild,- // i18next calls it language, but it really is the locale- lng: locale,- // Tell i18next about the locales we support- supportedLngs: supportedLocales,- // Ask it to fetch only exact matches- //- // By default, if the lng was set to, say, en-GB, i18n would make- // network requests for ["en-GB", "en", "dev"] (where dev is the- // default fallback). By setting `load` to "currentOnly", we ask- // i18next to only try and fetch "en-GB" (i.e. the exact match).- load: "currentOnly",- // Disallow empty strings as valid translations.- //- // This way, empty strings will fallback to `fallbackLng`- returnEmptyString: false,- // The language to use if translation for a particular key in the- // current `lng` is not available.- fallbackLng: defaultLocale,- interpolation: {- escapeValue: false, // not needed for react as it escapes by default- },- react: {- useSuspense: false,- // Allow the following tags (without any attributes) to be used- // in translations. Such keys can then be rendered using the- // Trans component, but without otherwise needing any other- // input from our side.- //- // https://react.i18next.com/latest/trans-component- transKeepBasicHtmlNodesFor: ["br", "p", "strong", "code"],- },- });-- // To use this in a translation, interpolate as `{{val, date}}`.- i18n.services.formatter?.addCached("date", (locale) => {- // The "long" dateStyle:- //- // - Includes: year (y), long-month (MMMM), day (d)- // - English pattern examples: MMMM d, y ("September 14, 1999")- //- const formatter = Intl.DateTimeFormat(locale, { dateStyle: "long" });- // Value is an epoch microsecond so that we can directly pass the- // timestamps we get from our API responses. The formatter expects- // milliseconds, so divide by 1000.- //- // See [Note: Remote timestamps are epoch microseconds].- return (val) => formatter.format(val / 1000);- });-};--/**- * Return the closest / best matching {@link SupportedLocale}.- *- * It takes as input a {@link savedLocaleString}, which denotes the user's- * explicitly chosen preference (which we then persist in local storage).- * Subsequently, we use this to (usually literally) return the supported locale- * that it represents.- *- * If {@link savedLocaleString} is `undefined`, it tries to deduce the closest- * {@link SupportedLocale} that matches the browser's locale.- */-const closestSupportedLocale = (- savedLocaleString?: string,-): SupportedLocale => {- const ss = savedLocaleString;- if (ss && includes(supportedLocales, ss)) return ss;-- for (const ls of getUserLocales()) {- // Exact match- if (ls && includes(supportedLocales, ls)) return ls;-- // Language match- if (ls.startsWith("en")) {- return "en-US";- } else if (ls.startsWith("fr")) {- return "fr-FR";- } else if (ls.startsWith("de")) {- return "de-DE";- } else if (ls.startsWith("ca")) {- return "ca-ES";- } else if (ls.startsWith("zh")) {- return "zh-CN";- } else if (ls.startsWith("nl")) {- return "nl-NL";- } else if (ls.startsWith("es")) {- return "es-ES";- } else if (ls.startsWith("pt-BR")) {- // We'll never get here (it'd already be an exact match), just kept- // to keep this list consistent.- return "pt-BR";- } else if (ls.startsWith("pt")) {- return "pt-PT";- } else if (ls.startsWith("ru")) {- return "ru-RU";- } else if (ls.startsWith("pl")) {- return "pl-PL";- } else if (ls.startsWith("it")) {- return "it-IT";- } else if (ls.startsWith("lt")) {- return "lt-LT";- } else if (ls.startsWith("uk")) {- return "uk-UA";- } else if (ls.startsWith("vi")) {- return "vi-VN";- } else if (ls.startsWith("ja")) {- return "ja-JP";- } else if (ls.startsWith("ar")) {- return "ar-SA";- } else if (ls.startsWith("tr")) {- return "tr-TR";- } else if (ls.startsWith("cs")) {- return "cs-CZ";- } else if (ls.startsWith("el")) {- return "el-GR";- }- }-- // Fallback- return defaultLocale;-};--/**- * Return the locale that is currently being used to show the app's UI.- *- * Note that this may be different from the user's locale. For example, the- * browser might be set to en-GB, but since we don't support that specific- * variant of English, this value will be (say) en-US.- */-export const getLocaleInUse = (): SupportedLocale => {- const locale = i18n.resolvedLanguage;- if (locale && includes(supportedLocales, locale)) {- return locale;- } else {- // This shouldn't have happened. Log an error to attract attention.- log.error(- `Expected the i18next locale to be one of the supported values, but instead found ${locale}`,- );- return defaultLocale;- }-};--/**- * Set the locale that should be used to show the app's UI.- *- * This updates both the i18next state, and also the corresponding user- * preference that is stored in local storage.- */-export const setLocaleInUse = async (locale: SupportedLocale) => {- localStorage.setItem("locale", locale);- return i18n.changeLanguage(locale);-};--let _numberFormat: Intl.NumberFormat | undefined;--/**- * Lazily created, cached, instance of NumberFormat used by- * {@link formattedNumber}.- *- * See: [Note: Changing locale causes a full reload].- */-const numberFormat = () =>- (_numberFormat ??= new Intl.NumberFormat(i18n.language));--/**- * Return the given {@link value} formatted for the current language and locale.- *- * In most cases, when a number needs to be displayed, it can be formatted as- * part of the surrounding string using the {{count, number}} interpolation.- * However, in some rare cases, we need to format a standalone number. For such- * scenarios, this function can be used.- */-export const formattedNumber = (value: number) => numberFormat().format(value);--let _listJoinFormat: Intl.ListFormat | undefined;--/**- * Lazily created, cached, instance of NumberFormat used by- * {@link formattedListJoin}.- *- * See: [Note: Changing locale causes a full reload].- */-const listJoinFormat = () =>- (_listJoinFormat ??= new Intl.ListFormat(i18n.language, {- style: "narrow",- }));--/**- * Return the given {@link items} joined together into a single string using an- * locale specific "comma like" separator.- *- * Usually this will just use a comma (plus space) as the list item separator,- * but depending on the locale it might use a different separator too.- *- * e.g. ["Foo", "Bar"] becomes "Foo, Bar" in "en-US" and "Foo、Bar" in "zh".- */-export const formattedListJoin = (value: string[]) =>- listJoinFormat().format(value);--/**- * A no-op marker for strings that, for various reasons, pending addition to the- * translation dataset.- *- * This function does nothing, it just returns back the passed it string- * verbatim. It is only kept as a way for us to keep track of strings which- * we've not yet added to the list of strings that should be translated (e.g.- * perhaps we're awaiting feedback on the copy).- *- * It is the sibling of the {@link t} function provided by i18next.- *- * See also: {@link ut}.- */-export const pt = (s: string) => s;--/**- * A no-op marker for strings that, for various reasons, are not translated.- *- * This function does nothing, it just returns back the passed it string- * verbatim. It is only kept as a way for us to keep track of strings that are- * not translated (and for some reason, are currently not meant to be), but- * still are user visible.- *- * It is the sibling of the {@link t} function provided by i18next.- *- * See also: {@link pt}.- */-export const ut = (s: string) => s;diff --git a/web/apps/albums/vendor/ente-base/id.ts b/web/apps/albums/vendor/ente-base/id.tsdeleted file mode 100644index 025d4344e0..0000000000--- a/web/apps/albums/vendor/ente-base/id.ts+++ /dev/null@@ -1,24 +0,0 @@-import { customAlphabet } from "nanoid";--/**- * Remove _ and - from the default set to have better looking IDs that can also- * be selected in the editor quickly ("-" prevents this), and which we can- * prefix unambiguously ("_" is used for that).- *- * To compensate, increase length from the default of 21 to 22.- *- * To play around with these, use https://zelark.github.io/nano-id-cc/- */-export const alphabet =- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";--const nanoid = customAlphabet(alphabet, 22);--/**- * Generate a new random identifier with the given prefix.- *- * Internally this uses [nanoids](https://github.com/ai/nanoid).- *- * See {@link newNonSecureID} for a variant that can be used in web workers.- */-export const newID = (prefix: string) => prefix + nanoid();diff --git a/web/apps/albums/vendor/ente-base/kv.ts b/web/apps/albums/vendor/ente-base/kv.tsdeleted file mode 100644index 3a05e6ffb1..0000000000--- a/web/apps/albums/vendor/ente-base/kv.ts+++ /dev/null@@ -1,186 +0,0 @@-import { deleteDB, openDB, type DBSchema } from "idb";-import log from "./log";--/**- * Key value store schema.- *- * [Note: KV DB]- *- * The use IndexedDB to store arbitrary key-value pairs. The functional- * motivation is to allow these to also be accessed from web workers (local- * storage is limited to the main thread).- *- * The "kv" database consists of one object store, "kv". Keys are strings.- * Values can be arbitrary JSON objects.- *- * [Note: Avoiding IndexedDB flakiness by avoiding indexes]- *- * Sporadically, rarely, but definitely, we ran into issues with IndexedDB- * losing data. e.g. saves from the ML web worker would complete successfully,- * but the saves would not reflect on the main thread, and that data would just- * get lost when the app would refresh.- *- * I'm not sure where the problem lay - in our own code, in the library that we- * are using (idb), within IndexedDB itself, or in Electron/Chrome's- * implementation of it (these cases all came up in the context of the ML code- * that only ran in our desktop app).- *- * A piece of advice I randomly ran across on the internet was to keep it very- * simple, and avoid all indexes. I also recalled that we did not see such- * issues with our older (but now unmaintained) library, localforage, which also- * doesn't use any indexes, and just has a flat single-store schema.- *- * So this may be superstition, but for now the approach I'm taking is to use- * IndexedDB as a key value store only.- */-interface KVDBSchema extends DBSchema {- kv: {- key: string;- /**- * Typescript doesn't have a native JSON type, so this needs to be- * unknown- */- value: unknown;- };-}--/**- * A lazily-created, cached promise for KV DB.- *- * [Note: Caching IDB instances in separate execution contexts]- *- * We open the database once (on access), and thereafter save and reuse this- * promise each time something wants to connect to it.- *- * This promise can subsequently get cleared if we need to relinquish our- * connection (e.g. if another client wants to open the face DB with a newer- * version of the schema).- *- * It can also get cleared on logout. In all such cases, it'll automatically get- * recreated on next access.- *- * Note that this is module specific state, so each execution context (main- * thread, web worker) that calls the functions in this module will its own- * promise to the database. To ensure that all connections get torn down- * correctly, we need to perform the following logout sequence:- *- * 1. Terminate all the workers which might have one of the instances in memory.- * This closes their connections.- *- * 2. Delete the database on the main thread.- */-let _kvDB: ReturnType<typeof openKVDB> | undefined;--const openKVDB = async () => {- const db = await openDB<KVDBSchema>("kv", 1, {- upgrade(db) {- db.createObjectStore("kv");- },- blocking() {- log.info(- "Another client is attempting to open a new version of KV DB",- );- db.close();- _kvDB = undefined;- },- blocked() {- log.warn(- "Waiting for an existing client to close their connection so that we can update the KV DB version",- );- },- terminated() {- log.warn("Our connection to KV DB was unexpectedly terminated");- _kvDB = undefined;- },- });-- return db;-};--/**- * @returns a lazily created, cached connection to the KV DB.- */-const kvDB = () => (_kvDB ??= openKVDB());--/**- * Clear all key values stored in the KV db.- *- * This is meant to be called during logout in the main thread.- */-export const clearKVDB = async () => {- try {- if (_kvDB) (await _kvDB).close();- } catch (e) {- log.warn("Ignoring error when trying to close KV DB", e);- }- _kvDB = undefined;-- return deleteDB("kv", {- blocked() {- log.warn(- "Waiting for an existing client to close their connection so that we can delete the KV DB",- );- },- });-};--/**- * Return the string value stored corresponding to {@link key}, or `undefined`- * if there is no such entry.- *- * Typescript doesn't have a native JSON type, so the return value is type as an- * `unknown`. For primitive types, you can avoid casting by using the- * {@link getKVS} (string), {@link getKVN} (number) or {@link getKVB} (boolean)- * methods that do an additional runtime check of the type.- */-export const getKV = async (key: string) => {- const db = await kvDB();- return db.get("kv", key);-};--const _getKV = async <T extends string | number | boolean>(- key: string,- type: string,-): Promise<T | undefined> => {- const db = await kvDB();- const v = await db.get("kv", key);- if (v === undefined) return undefined;- if (typeof v != type)- throw new Error(- // This is just an error message, it is fine if stringification- // produces nothing useful always, it might too in some cases.- //- // eslint-disable-next-line @typescript-eslint/no-base-to-string- `Expected the value corresponding to key ${key} to be a ${type}, but instead got ${String(v)}`,- );- return v as T;-};--/** String variant of {@link getKV}. */-export const getKVS = async (key: string) => _getKV<string>(key, "string");--/** Numeric variant of {@link getKV}. */-export const getKVN = async (key: string) => _getKV<number>(key, "number");--/** Boolean variant of {@link getKV} */-export const getKVB = async (key: string) => _getKV<boolean>(key, "boolean");--/**- * Save the given {@link value} corresponding to {@link key}, overwriting any- * existing value.- *- * @param value Any arbitrary JSON object. Typescript doesn't have a native JSON- * type, so this is typed as a unknown- */-export const setKV = async (key: string, value: unknown) => {- const db = await kvDB();- await db.put("kv", value, key);-};--/**- * Remove the entry corresponding to {@link key} (if any).- */-export const removeKV = async (key: string) => {- const db = await kvDB();- await db.delete("kv", key);-};diff --git a/web/apps/albums/vendor/ente-base/log-web.ts b/web/apps/albums/vendor/ente-base/log-web.tsdeleted file mode 100644index c500f58686..0000000000--- a/web/apps/albums/vendor/ente-base/log-web.ts+++ /dev/null@@ -1,143 +0,0 @@-import { isDevBuild } from "ente-base/env";-import log from "ente-base/log";-import { appName } from "./app";--/**- * Log a standard startup banner.- *- * This helps us identify app starts and other environment details in the logs.- *- * @param userID The uid for the currently logged in user, if any.- */-export const logStartupBanner = (userID?: number) => {- const sha = process.env.gitSHA;- const buildID = isDevBuild ? "dev " : sha ? `git ${sha} ` : "";- log.info(`Starting ente-${appName}-web ${buildID}uid ${userID ?? 0}`);-};--/**- * Attach handlers to log any unhandled exceptions and promise rejections.- *- * @param attach If true, attach handlers, and if false, remove them. This- * allows us to use this in a React hook that cleans up after itself.- */-export const logUnhandledErrorsAndRejections = (attach: boolean) => {- const handleError = (event: ErrorEvent) => {- // [Note: Spurious media chrome resize observer errors]- //- // When attaching media chrome controls to the DOM, we get an (AFAICT)- // spurious error in the log. Ignore it. FWIW, the media control tests- // themselves do the same.- // https://github.com/muxinc/elements/blob/f602519f544509f15add8fcc8cbbf7379843dcd3/packages/mux-player/test/player.test.js#L6-L12C5- if (- event.message ==- "ResizeObserver loop completed with undelivered notifications."- ) {- return;- }-- log.error("Unhandled error", event.error ?? event.message);- };-- const handleUnhandledRejection = (event: PromiseRejectionEvent) => {- log.error("Unhandled promise rejection", event.reason);- };-- if (attach) {- window.addEventListener("error", handleError);- window.addEventListener("unhandledrejection", handleUnhandledRejection);- } else {- window.removeEventListener("error", handleError);- window.removeEventListener(- "unhandledrejection",- handleUnhandledRejection,- );- }-};--/**- * Attach handlers to log any unhandled exceptions and promise rejections in web- * workers.- *- * This is a variant of {@link logUnhandledErrorsAndRejections} that works in- * web workers. It should be called at the top level of the main worker script.- *- * Note: When I tested this, attaching the onerror handler to the worker outside- * the worker (e.g. when creating it in comlink-worker.ts) worked, but attaching- * the "unhandledrejection" event there did not work. Attaching them to `self`- * (the {@link WorkerGlobal}) worked.- */-export const logUnhandledErrorsAndRejectionsInWorker = () => {- const handleError = (event: ErrorEvent) => {- log.error("Unhandled error", event.error);- };-- const handleUnhandledRejection = (event: PromiseRejectionEvent) => {- log.error("Unhandled promise rejection", event.reason);- };-- self.addEventListener("error", handleError);- self.addEventListener("unhandledrejection", handleUnhandledRejection);-};--interface LogEntry {- timestamp: number;- logLine: string;-}--const lsKey = "logs";--/**- * Record {@link message} in a persistent log storage.- *- * These strings, alongwith associated timestamps, get added to a small ring- * buffer, whose contents can be later be retrieved by using {@link savedLogs}.- *- * This ring buffer is persisted in the browser's local storage.- */-export const logToDisk = (message: string) => {- const maxCount = 1000;- const log: LogEntry = { logLine: message, timestamp: Date.now() };- try {- const logs = logEntries();- if (logs.length > maxCount) {- logs.slice(logs.length - maxCount);- }- logs.push(log);- localStorage.setItem(lsKey, JSON.stringify({ logs }));- } catch (e) {- console.error("Failed to persist log", e);- if (e instanceof Error && e.name == "QuotaExceededError") {- localStorage.removeItem(lsKey);- }- }-};--const logEntries = (): unknown[] => {- const s = localStorage.getItem("logs");- if (!s) return [];- const o: unknown = JSON.parse(s);- if (!(o && typeof o == "object" && "logs" in o && Array.isArray(o.logs))) {- console.error("Unexpected log entries obtained from local storage", o);- return [];- }- return o.logs;-};--/**- * Return a string containing all recently saved log messages.- *- * @see {@link persistLog}.- */-export const savedLogs = () => logEntries().map(formatEntry).join("\n");--const formatEntry = (e: unknown) => {- if (e && typeof e == "object" && "timestamp" in e && "logLine" in e) {- const timestamp = e.timestamp;- const logLine = e.logLine;- if (typeof timestamp == "number" && typeof logLine == "string") {- return `[${new Date(timestamp).toISOString()}] ${logLine}`;- }- }- return String(e);-};diff --git a/web/apps/albums/vendor/ente-base/log.ts b/web/apps/albums/vendor/ente-base/log.tsdeleted file mode 100644index 708cbbdb31..0000000000--- a/web/apps/albums/vendor/ente-base/log.ts+++ /dev/null@@ -1,170 +0,0 @@-import { inWorker } from "ente-base/env";-import { isDevBuild } from "./env";-import { logToDisk as webLogToDisk } from "./log-web";-import { workerBridge } from "./worker/worker-bridge";--/**- * Whether logs go to disk or are always emitted to the console.- */-let shouldLogToDisk = true;--/**- * By default, logs get saved into a ring buffer in the browser's local storage.- * However, in some contexts, e.g. when we're running as the cast app, there is- * no mechanism for the user to retrieve these logs. So this function exists as- * a way to disable the on disk logging and always use the console.- */-export const disableDiskLogs = () => (shouldLogToDisk = false);--/**- * Write a {@link message} to the on-disk log.- *- * This is used by the renderer process (via the contextBridge) to add entries- * in the log that is saved on disk.- */-export const logToDisk = (message: string) => {- if (inWorker()) workerLogToDisk(message);- else webLogToDisk(message);-};--const workerLogToDisk = (message: string) => {- workerBridge!.logToDisk(message).catch((e: unknown) => {- console.error(- "Failed to log a message from worker",- e,- "\nThe message was",- message,- );- });-};--const messageWithError = (message: string, e?: unknown) => {- if (!e) return message;-- let es: string;- if (e instanceof Error) {- // In practice, we expect ourselves to be called with Error objects, so- // this is the happy path so to say.- es = `${e.name}: ${e.message}`;- const st = e.stack;- if (st) {- // On V8 (as of 2024), the stack trace begins by repeating the error's- // name and message, trim that off.- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack- es = st.startsWith(es)- ? es.concat(st.slice(es.length)) /* retain the '\n' */- : [es, st].join("\n");- }- } else {- // For the rest rare cases, use the default string serialization of e.- // eslint-disable-next-line @typescript-eslint/no-base-to-string- es = String(e);- }-- return `${message}: ${es}`;-};--const logError = (message: unknown, e?: unknown) => {- const m =- typeof message == "string"- ? `[error] ${messageWithError(message, e)}`- : `[error] ${messageWithError("Error", message)}`;- console.error(m);- if (shouldLogToDisk) logToDisk(m);-};--const logWarn = (message: string, e?: unknown) => {- const m = `[warn] ${messageWithError(message, e)}`;- console.error(m);- if (shouldLogToDisk) logToDisk(m);-};--const logInfo = (...params: unknown[]) => {- const message = params- .map((p) => (typeof p == "string" ? p : JSON.stringify(p)))- .join(" ");- const m = `[info] ${message}`;- if (isDevBuild || !shouldLogToDisk) console.log(m);- if (shouldLogToDisk) logToDisk(m);-};--const logDebug = (param: () => unknown) => {- if (isDevBuild) {- const p = param();- // Transform- // log.debug(() => ["tag", {x: y}])- // =>- // console.log("[debug] tag", {x: y})- if (Array.isArray(p)) {- // tseslint is not happy with us for destructuring any, but this is- // non-production dev build only code, so silence it and go ahead.- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment- const [tag, ...rest] = p;- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument- console.log(`[debug] ${tag}`, ...rest);- } else {- /* Let console.log serialize it */- console.log("[debug]", p);- }- }-};--/**- * Ente's logger.- *- * This is an object that provides functions to log at the corresponding levels:- * error, warn, info or debug.- *- * Whenever we need to save a log message to disk,- *- * Messages are written to a ring buffer in local storage, and proxied back to- * the main thread when emitted from workers.- */-export default {- /**- * Log an error message with an optional associated error object.- *- * {@link e} is generally expected to be an `instanceof Error` but it can be- * any arbitrary object that we obtain, say, when in a try-catch handler (in- * JavaScript any arbitrary value can be thrown).- *- * If only one argument is specified, and it is not a string, then it is- * taken as the error to be printed, paired with a generic message.- *- * The log is written to disk and printed to the browser console.- */- error: logError,- /**- * Sibling of {@link error}, with the same parameters and behaviour, except- * it gets prefixed with a warning instead of an error tag.- */- warn: logWarn,- /**- * Log a message.- *- * This is meant as a replacement of {@link console.log}, and takes an- * arbitrary number of arbitrary parameters that it then serializes.- *- * The log is written to disk. However, if logging to disk is disabled by- * using {@link disableDiskLogs}, then the log is printed to the console.- *- * In development builds, the log is always printed to the browser console.- */- info: logInfo,- /**- * Log a debug message.- *- * To avoid running unnecessary code in release builds, this takes a- * function to call to get the log message instead of directly taking the- * message. The provided function will only be called in development builds.- *- * The function can return an arbitrary value which is serialized before- * being logged. As a special case, arrays are spread, which allows one to- * write `log.debug(() => ["tag", {x: y}])` and have that be printed as if- * it were `console.log("[debug] tag", {x: y})`.- *- * This log is NOT written to disk. It is printed to the browser console,- * but only in development builds.- */- debug: logDebug,-};diff --git a/web/apps/albums/vendor/ente-base/origins.ts b/web/apps/albums/vendor/ente-base/origins.tsdeleted file mode 100644index 1185534397..0000000000--- a/web/apps/albums/vendor/ente-base/origins.ts+++ /dev/null@@ -1,115 +0,0 @@-import { getKVS } from "ente-base/kv";--/**- * Return the origin (scheme, host, port triple) that should be used for making- * API requests to museum.- *- * This defaults "https://api.ente.io", Ente's production API servers. but can- * be overridden when self hosting or developing (see {@link customAPIOrigin}).- */-export const apiOrigin = async () =>- (await customAPIOrigin()) ?? "https://api.ente.io";--/**- * A convenience function to construct an endpoint in a one-liner.- *- * This avoids us having to create a temporary variable or otherwise complicate- * the call sites since async functions cannot be used inside template literals.- *- * @param path The URL path usually, but can be anything that needs to be- * suffixed to the origin. It must begin with a "/".- *- * @param queryParams An optional object containing query params. This is- * appended to the generated URL after funneling it through- * {@link URLSearchParams}. Each value can be a `string` or `number` or- * `boolean` - all of which are converted to `string`s by using `toString`- *- * > The boolean stringification yields "true" or "false".- *- * @returns path prefixed by {@link apiOrigin}.- */-export const apiURL = async (- path: string,- queryParams?: Record<string, string | number | boolean>,-) => {- let url = (await apiOrigin()) + path;- if (queryParams) {- const stringQP = Object.fromEntries(- Object.entries(queryParams).map(([k, v]) => [k, v.toString()]),- );- const params = new URLSearchParams(stringQP);- url = `${url}?${params.toString()}`;- }- return url;-};--/**- * Return the overridden API origin, if one is defined by either (in priority- * order):- *- * - Setting the custom server on the landing page (See: [Note: Configuring- * custom server]); or by- *- * - Setting the `NEXT_PUBLIC_ENTE_ENDPOINT` environment variable.- *- * Otherwise return undefined.- */-export const customAPIOrigin = async () =>- (await getKVS("apiOrigin")) ??- process.env.NEXT_PUBLIC_ENTE_ENDPOINT ??- undefined;--/**- * A convenience wrapper over {@link customAPIOrigin} that returns the only the- * host part of the custom origin (if any).- *- * This is useful in places where we indicate the custom origin in the UI.- */-export const customAPIHost = async () => {- const origin = await customAPIOrigin();- return origin ? new URL(origin).host : undefined;-};--/**- * Return the origin that should be used for uploading files.- *- * This defaults to `https://uploader.ente.io`, serviced by a Cloudflare worker- * (see infra/workers/uploader). But if a {@link customAPIOrigin} is set then- * this value is set to the {@link customAPIOrigin} itself, effectively- * bypassing the Cloudflare worker for non-Ente deployments.- */-export const uploaderOrigin = async () =>- (await customAPIOrigin()) ?? "https://uploader.ente.io";--/**- * A static build time constant that is `true` if {@link albumsAppOrigin} has- * been customized.- */-export const isCustomAlbumsAppOrigin =- !!process.env.NEXT_PUBLIC_ENTE_ALBUMS_ENDPOINT;--/**- * Return the origin that serves public albums.- *- * Defaults to our production instance, "https://albums.ente.io", but can be- * overridden by setting the `NEXT_PUBLIC_ENTE_ALBUMS_ENDPOINT` environment- * variable.- */-export const albumsAppOrigin = () =>- process.env.NEXT_PUBLIC_ENTE_ALBUMS_ENDPOINT ?? "https://albums.ente.io";--/**- * Return true if this build is Ente's official public albums deployment.- */-export const isOfficialAlbumsApp =- !!process.env.NEXT_PUBLIC_ENTE_OFFICIAL_ALBUMS_APP;--/**- * Return the origin that serves the photos app.- *- * Defaults to our production instance, "https://web.ente.io", but can be- * overridden by setting the `NEXT_PUBLIC_ENTE_PHOTOS_ENDPOINT` environment- * variable.- */-export const photosAppOrigin = (): string =>- process.env.NEXT_PUBLIC_ENTE_PHOTOS_ENDPOINT ?? "https://web.ente.io";diff --git a/web/apps/albums/vendor/ente-base/session.ts b/web/apps/albums/vendor/ente-base/session.tsdeleted file mode 100644index 28153238c6..0000000000--- a/web/apps/albums/vendor/ente-base/session.ts+++ /dev/null@@ -1,46 +0,0 @@-import { z } from "zod";-import { decryptBox, encryptBox, generateKey } from "./crypto";--export const clearSessionStorage = () => sessionStorage.clear();--const SessionKeyData = z.object({- encryptedData: z.string(),- key: z.string(),- nonce: z.string(),-});--type SessionKeyData = z.infer<typeof SessionKeyData>;--const sessionKeyData = async (keyData: string): Promise<SessionKeyData> => {- const key = await generateKey();- const box = await encryptBox(keyData, key);- return { key, ...box };-};--const sessionKey = async (keyName: string) => {- const value = sessionStorage.getItem(keyName);- if (!value) return undefined;-- const { encryptedData, key, nonce } = SessionKeyData.parse(- JSON.parse(value),- );- return decryptBox({ encryptedData, nonce }, key);-};--export const ensureMasterKeyFromSession = async () => {- const key = await masterKeyFromSession();- if (!key) throw new Error("Master key not found in session");- return key;-};--export const haveMasterKeyInSession = () =>- !!sessionStorage.getItem("encryptionKey");--export const masterKeyFromSession = async () => sessionKey("encryptionKey");--export const saveMasterKeyInSession = async (masterKey: string) => {- sessionStorage.setItem(- "encryptionKey",- JSON.stringify(await sessionKeyData(masterKey)),- );-};diff --git a/web/apps/albums/vendor/ente-base/token.ts b/web/apps/albums/vendor/ente-base/token.tsdeleted file mode 100644index 109322b339..0000000000--- a/web/apps/albums/vendor/ente-base/token.ts+++ /dev/null@@ -1,42 +0,0 @@-import { getKVS, removeKV, setKV } from "./kv";--/**- * Return the user's auth token, or throw an error.- *- * The user's auth token can be retrieved using {@link savedAuthToken}. This- * function is a wrapper which throws an error if the token is not found (which- * should only happen if the user is not logged in).- */-export const ensureAuthToken = async () => {- const token = await savedAuthToken();- if (!token) throw new Error("Not logged in");- return token;-};--/**- * Return the user's auth token, if available.- *- * The user's auth token is stored in KV DB using {@link saveAuthToken} during- * the login / signup flow. This function returns that saved auth token.- *- * The underlying data is stored in IndexedDB, and can be accessed from web- * workers.- *- * If your code is running in a context where the user is already expected to be- * logged in, use {@link ensureAuthToken} instead.- */-export const savedAuthToken = () => getKVS("token");--/**- * Save the user's auth token in KV DB.- *- * This is the setter corresponding to {@link savedAuthToken}.- */-export const saveAuthToken = (token: string) => setKV("token", token);--/**- * Remove the user's auth token from KV DB.- *- * See {@link saveAuthToken}.- */-export const removeAuthToken = () => removeKV("token");diff --git a/web/apps/albums/vendor/ente-base/types/index.ts b/web/apps/albums/vendor/ente-base/types/index.tsdeleted file mode 100644index 10dc83fa67..0000000000--- a/web/apps/albums/vendor/ente-base/types/index.ts+++ /dev/null@@ -1,7 +0,0 @@-/**- * A location, represented as a (latitude, longitude) pair.- */-export interface Location {- latitude: number;- longitude: number;-}diff --git a/web/apps/albums/vendor/ente-base/utils/web.ts b/web/apps/albums/vendor/ente-base/utils/web.tsdeleted file mode 100644index f0120f4a35..0000000000--- a/web/apps/albums/vendor/ente-base/utils/web.ts+++ /dev/null@@ -1,34 +0,0 @@-/**- * Download the asset at the given {@link url} to a file on the user's download- * folder by appending a temporary <a> element to the DOM.- *- * @param url The URL that we want to download. The URL is revoked after- * initiating the download.- *- * @param fileName The name of downloaded file.- *- * See also {@link saveStringAsFile}.- */-export const saveAsFileAndRevokeObjectURL = (url: string, fileName: string) => {- const a = document.createElement("a");- a.style.display = "none";- a.href = url;- a.download = fileName;- document.body.appendChild(a);- a.click();- URL.revokeObjectURL(url);- a.remove();-};--/**- * Save the given string {@link s} as a file in the user's download folder.- *- * @param s The string to save.- *- * @param fileName The name of the file that gets saved.- */-export const saveStringAsFile = (s: string, fileName: string) => {- const file = new Blob([s], { type: "text/plain" });- const fileURL = URL.createObjectURL(file);- saveAsFileAndRevokeObjectURL(fileURL, fileName);-};diff --git a/web/apps/albums/vendor/ente-base/worker/comlink-worker.ts b/web/apps/albums/vendor/ente-base/worker/comlink-worker.tsdeleted file mode 100644index 7f57765df7..0000000000--- a/web/apps/albums/vendor/ente-base/worker/comlink-worker.ts+++ /dev/null@@ -1,34 +0,0 @@-import { expose, wrap, type Remote } from "comlink";-import log, { logToDisk } from "ente-base/log";--export class ComlinkWorker<T extends new () => InstanceType<T>> {- public remote: Promise<Remote<InstanceType<T>>>;- public worker: Worker;- private name: string;-- constructor(name: string, worker: Worker) {- this.name = name;- this.worker = worker;-- worker.onerror = (event) => {- log.error(- `Got error event from worker: ${JSON.stringify({ event, name })}`,- );- };- log.debug(() => `Created ${name} web worker`);- const comlink = wrap<T>(worker);- this.remote = new comlink() as Promise<Remote<InstanceType<T>>>;- expose(workerBridge, worker);- }-- public terminate() {- this.worker.terminate();- log.debug(() => `Terminated ${this.name} web worker`);- }-}--const workerBridge = {- logToDisk,-};--export type WorkerBridge = typeof workerBridge;diff --git a/web/apps/albums/vendor/ente-base/worker/worker-bridge.ts b/web/apps/albums/vendor/ente-base/worker/worker-bridge.tsdeleted file mode 100644index eaf3028ea4..0000000000--- a/web/apps/albums/vendor/ente-base/worker/worker-bridge.ts+++ /dev/null@@ -1,15 +0,0 @@-import { wrap } from "comlink";-import { inWorker } from "../env";-import type { WorkerBridge } from "./comlink-worker";--/**- * The web worker side handle to the {@link WorkerBridge} exposed by the main- * thread.- *- * This file is meant to be run inside a worker. Accessing the properties of- * this object will be transparently (but asynchrorously) relayed to the- * implementation of the {@link WorkerBridge} in `comlink-worker.ts`.- */-export const workerBridge = inWorker()- ? wrap<WorkerBridge>(globalThis)- : undefined;diff --git a/web/apps/albums/vendor/ente-media/collection.ts b/web/apps/albums/vendor/ente-media/collection.tsdeleted file mode 100644index d3cc500ae1..0000000000--- a/web/apps/albums/vendor/ente-media/collection.ts+++ /dev/null@@ -1,741 +0,0 @@-import { decryptBoxBytes } from "ente-base/crypto";-import {- nullishToEmpty,- nullishToFalse,- nullToUndefined,-} from "ente-utils/transform";-import { z } from "zod";-import {- decryptMagicMetadata,- RemoteMagicMetadata,- type MagicMetadata,-} from "./magic-metadata";--/**- * A collection, as used and persisted locally by the client.- *- * A collection is, well, a collection of files. It is roughly equivalent to an- * "album" (which is also the term we use in the UI), but there can also be- * special type of collections like "favorites" which have special behaviour.- *- * A collection contains zero or more files ({@link EnteFile}).- *- * A collection can be owned by the user (in whose context this code is- * running), or might be a collection that is shared with them.- */-export interface Collection {- /**- * The collection's globally unique ID.- *- * The collection's ID is a integer assigned by remote as the identifier for- * an {@link Collection} when it is created. It is globally unique across- * all collections on an Ente instance (i.e., it is not scoped to a user).- */- id: number;- /**- * Information about the user who owns the collection.- *- * Each collection is owned by exactly one user. The owner may optionally- * choose to share it with additional users, granting them varying level of- * privileges.- *- * Within the {@link CollectionUser} instance of the {@link owner} field:- *- * - {@link email} will be set only if this is a shared collection that does- * not belong to the current user.- * - {@link role} will be blank.- */- owner: CollectionUser;- /**- * The "collection key" (base64 encoded).- *- * The collection key is used to encrypt and decrypt that files that are- * associated with the collection. See: [Note: Collection file].- */- key: string;- /**- * The name of the collection.- */- name: string;- /**- * The type of the collection.- *- * Expected to be one of {@link CollectionType}.- */- type: string;- /**- * The other Ente users with whom the collection has been shared with.- *- * Within the {@link CollectionUser} instances of the {@link sharee} field:- *- * - {@link email} will be set.- * - {@link role} is expected to be one of "VIEWER" or "COLLABORATOR".- */- sharees: CollectionUser[];- /**- * Public links that can be used to access and update the collection.- */- publicURLs: PublicURL[];- /**- * The last time the collection was updated (epoch microseconds).- *- * The collection is considered updated both- *- * - When the files associated with it modified (added, removed); and- * - When the collection's own fields are modified.- */- updationTime: number;- /**- * Private mutable metadata associated with the collection that is only- * visible to the owner of the collection.- *- * See: [Note: Metadatum]- */- magicMetadata?: MagicMetadata<CollectionPrivateMagicMetadataData>;- /**- * Public mutable metadata associated with the collection that is visible to- * all users with whom the collection has been shared.- *- * See: [Note: Metadatum]- */- pubMagicMetadata?: MagicMetadata<CollectionPublicMagicMetadataData>;- /**- * Private mutable metadata associated with the collection that is only- * visible to the current user if they're not the owner of the collection.- *- * Sometimes also referred to as "shareeMagicMetadata".- *- * This is metadata associated with each "share", and is only visible to- * (and editable by) the user with which the collection has been shared, not- * the owner. Each user with whom the collection has been shared gets their- * own private copy. This allows each user to keep their own metadata- * associated with a shared album (e.g. archive status).- *- * See: [Note: Metadatum]- */- sharedMagicMetadata?: MagicMetadata<CollectionShareeMagicMetadataData>;-}--/**- * The known set of values for the {@link type} field of a {@link Collection}.- *- * This is the list of values, see {@link CollectionType} for the corresponding- * TypeScript type.- */-export const collectionTypes = [- "album",- "folder",- "favorites",- "uncategorized",-] as const;--/**- * The type of a collection.- *- * - "album" - A regular "Ente Album" that the user sees in their library.- *- * - "folder" - An Ente Album that is also associated with an OS album on the- * user's mobile device.- *- * A collection of type "folder" is created by the mobile app if there is an- * associated on-device album for the new Ente album being created.- *- * This separation between "album" and "folder" allows different mobile- * clients to push to the same Folder ("Camera", "Screenshots"), not allowing- * for duplicate folders with the same name, while still allowing users to- * create different albums with the same name.- *- * The web/desktop app does not create collections of type "folder", and- * otherwise treats them as aliases for "album".- *- * - "favorites" - A special collection consisting of the items that the user- * has marked as their favorites.- *- * The user can have at most one collection of type "favorites" (enforced at- * remote). This collection is created on demand by the client where the user- * first marks an item as a favorite. The user can choose to share their- * "favorites" with other users, so it is possible for there to be multiple- * collections of type "favorites" present in our local database, however only- * one of those will belong to the logged in user (cf `owner.id`).- *- * - "uncategorized" - A special collection consisting of items that do not- * belong to any other collection.- *- * In the remote schema, each item ({@link EnteFile}) is always associated- * with a collection. The same item may belong to multiple collections (See:- * [Note: Collection file]), but it must belong to at least one collection.- *- * In some scenarios, e.g. when deleting the last collection to which a file- * belongs, the file would thus get orphaned and violate the schema- * invariants. So in such cases, the client which is performing the- * corresponding operation moves the file to the user's special- * "uncategorized" collection, creating it if needed.- *- * Similar to "favorites", the user can have only one "uncategorized"- * collection. However, unlike "favorites", the "uncategorized" collection- * cannot be shared.- */-export type CollectionType = (typeof collectionTypes)[number];--/**- * The privilege level of a participant associated with a collection.- *- * - "VIEWER" - Has read-only access to files in the collection.- *- * - "COLLABORATOR" - Can additionally add files from the collection, and remove- * files that they added from the collection (i.e., files they "own").- *- * - "ADMIN" - Can manage participants (invite/remove) similar to the owner, but- * cannot delete the collection or remove the owner.- *- * - "OWNER" - The owner of the collection. Can remove any file, including those- * added by other users, from the collection.- *- * It is guaranteed that a there will be exactly one participant of type OWNER,- * and their user ID will be the same as the collection `owner.id`.- */-export type CollectionParticipantRole =- | "VIEWER"- | "COLLABORATOR"- | "ADMIN"- | "OWNER"- | "UNKNOWN";--/**- * A subset of {@link CollectionParticipantRole} that are applicable when- * sharing a collection with another Ente user.- */-export type CollectionNewParticipantRole = "VIEWER" | "COLLABORATOR" | "ADMIN";--/**- * Information about the user associated with a collection, either as an owner,- * or as someone with whom the collection has been shared with.- */-export interface CollectionUser {- /**- * The ID of the underlying {@link User} that this {@link CollectionUser}- * stands for.- */- id: number;- /**- * The email of the user.- *- * - The email is present for the {@link owner} only for shared collections- * that do not belong to the current user.- * - The email is present for all {@link sharees}.- * - Remote uses a blank string to indicate absent values.- */- email?: string;- /**- * The association / privilege level of the user with the collection.- *- * Expected to be one of {@link CollectionParticipantRole}.- *- * - The role is not present (blank string) for the {@link owner}.- * - The role is present, and one of "VIEWER" and "COLLABORATOR" for the- * {@link sharees}.- * - Remote uses a blank string to indicate absent values.- */- role?: string;-}--/**- * Zod schema for {@link CollectionUser}.- *- * [Note: Enums in remote objects]- *- * In some cases remote returns a value which is part of a known set. The- * underlying type might be an integer or a string.- *- * While Zod allows us to validate enum types during a parse, we refrain from- * doing this as this would cause existing clients to break if remote were to in- * the future add new enum cases.- *- * This is especially pertinent for objects which we might persist locally,- * since the client code which persists the object might not know about a- * particular enum case but a future client which reads the saved value might.- *- * So we keep the underlying data type (string or number) as it is instead of- * converting / validating to an enum or discarding unknown values.- *- * As an example consider the {@link role} item in {@link RemoteCollectionUser}.- * There is a known set of values ({@link CollectionParticipantRole}) this can- * be, but in the Zod schema we keep the data type as a string.- */-export const RemoteCollectionUser = z.looseObject({- id: z.number(),- email: z.string().nullish().transform(nullToUndefined),- role: z.string().nullish().transform(nullToUndefined),-});--type RemoteCollectionUser = z.infer<typeof RemoteCollectionUser>;--/**- * A public link for a shared collection.- *- * This structure contains a (partial^) URL that can be used to access the- * shared collection, along with other attributes of the link.- *- * ^ The URL is partial because it doesn't have the URL fragment, which is- * client side only as it contains the decryption key- */-export interface PublicURL {- /**- * A URL that can be used access the shared collection.- *- * This will be of the form "https://<public-albums-app>/?t=<token>", e.g.,- * "https://albums.ente.io/?t=xxxxxx".- *- * In particular, this URL does not contain the URL fragment (the part after- * the "#"). URL fragments are client side only, and not sent to remote.- * They contain the decryption key.- *- * The client can use this field to form the fully usable URL (e.g.- * "https://albums.ente.io/?t=xxxxxx#yyy...yyy") and provide it to the user- * for sharing.- */- url: string;- /**- * The number of unique devices which can access the collection using the- * public URL.- *- * Set to 0 to indicate no device limit.- */- deviceLimit: number;- /**- * The epoch microseconds until which the link is valid.- *- * Set to 0 to indicate no expiry.- */- validTill: number;- /**- * `true` if downloads are enabled from this link.- *- * When creating a new link this is `true` by default, and can optionally be- * disabled in the public link settings.- */- enableDownload: boolean;- enableJoin: boolean;- /**- * `true` if people can use the public link to upload new files to the- * shared collection.- */- enableCollect: boolean;- /**- * `true` if comments are enabled on this public link.- */- enableComment: boolean;- /**- * `true` if the link is password protected.- *- * When this is `true`, {@link nonce}, {@link memLimit} and {@link opsLimit}- * will also be set.- */- passwordEnabled: boolean;- /**- * The nonce to use when hashing the password.- *- * Only present when {@link passwordEnabled} is `true`.- */- nonce?: string;- /**- * The ops limit to use when hashing the password.- *- * Only present when {@link passwordEnabled} is `true`.- */- opsLimit?: number;- /**- * The mem limit to use when hashing the password.- *- * Only present when {@link passwordEnabled} is `true`.- */- memLimit?: number;-}--/**- * Zod schema for the {@link PublicURL} we use in our interactions with remote.- *- * We also use the same schema when persisting the collection locally.- */-export const RemotePublicURL = z.looseObject({- url: z.string(),- deviceLimit: z.number(),- validTill: z.number(),- enableDownload: z.boolean().nullish().transform(nullishToFalse),- enableJoin: z.boolean().nullish().transform(nullishToFalse),- enableCollect: z.boolean().nullish().transform(nullishToFalse),- enableComment: z.boolean().nullish().transform(nullishToFalse),- passwordEnabled: z.boolean().nullish().transform(nullishToFalse),- nonce: z.string().nullish().transform(nullToUndefined),- memLimit: z.number().nullish().transform(nullToUndefined),- opsLimit: z.number().nullish().transform(nullToUndefined),-});--/**- * Zod schema for {@link Collection}.- *- * [Note: Use looseObject when parsing JSON that will get persisted]- *- * While not always necessary, for a few cases (files and collections being the- * most prominent and important) we try to retain any unknown fields in the JSON- * we get from remote, so that future versions of the client with support for- * fields unbeknownst to the current one can read and use them.- *- * In such cases, the nested objects should also (recursively) use the- * looseObject schema. But not always - in some cases where the structures we- * use are well established, e.g. {@link RemoteMagicMetadata} - we use the- * default Zod behaviour of discarding unknown fields.- *- * > Note that even in the case of {@link RemoteMagicMetadata}, we still apply- * > looseObject to the payload itself.- * >- * > See: [Note: Use looseObject for metadata Zod schemas]- *- * Unlike metadata, where we do strictly want to retain unknown or unacted on- * fields, in the more general case we are okay with being a bit loose with- * looseObject, and even intentionally dropping fields that we know we're not- * going to use on the current client. Such looseness is okay because even if we- * need to use them in the future, we can always refetch the objects again- * (while in the case of metadata, we need to also push our changes to remote,- * so it is functionally important for us to retain the source verbatim).- */-export const RemoteCollection = z.looseObject({- id: z.number(),- owner: RemoteCollectionUser,- encryptedKey: z.string(),- /**- * The nonce to use when decrypting the {@link encryptedKey} when the album- * is owned by the user.- *- * Not set for shared albums (the decryption for uses the keypair instead).- *- * Remote might set this to blank to indicate absence.- */- keyDecryptionNonce: z.string().nullish().transform(nullToUndefined),- /**- * Expected to be present (along with {@link nameDecryptionNonce}), but it- * is still optional since it might not be present if {@link name} is present.- */- encryptedName: z.string().nullish().transform(nullToUndefined),- nameDecryptionNonce: z.string().nullish().transform(nullToUndefined),- /**- * Not used anymore, but still might be present for very old collections.- *- * Before public launch, collection names were stored unencrypted. For- * backward compatibility, client should use {@link name} if present,- * otherwise obtain it by decrypting it from {@link encryptedName} and- * {@link nameDecryptionNonce}.- */- name: z.string().nullish().transform(nullToUndefined),- /**- * Expected to be one of {@link CollectionType}- */- type: z.string(),- sharees: z.array(RemoteCollectionUser).nullish().transform(nullishToEmpty),- publicURLs: z.array(RemotePublicURL).nullish().transform(nullishToEmpty),- updationTime: z.number(),- /**- * Tombstone marker.- *- * This is set to `true` in the collection fetch response to indicate- * collections which have been deleted on remote and should thus be pruned- * by the client locally.- */- isDeleted: z.boolean().nullish().transform(nullToUndefined),- magicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),- pubMagicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),- sharedMagicMetadata:- RemoteMagicMetadata.nullish().transform(nullToUndefined),-});--export type RemoteCollection = z.infer<typeof RemoteCollection>;--/**- * Decrypt a remote collection using the provided {@link collectionKey}.- *- * @param collection The remote collection to decrypt.- *- * @param collectionKey The base64 encoded key to use for decrypting the various- * encrypted fields in {@link collection}.- *- * @returns A decrypted collection.- */-export const decryptRemoteCollection = async (- collection: RemoteCollection,- collectionKey: string,-): Promise<Collection> => {- // RemoteCollection is a looseObject, and we want to retain that semantic- // for the parsed Collection. Mention all fields that we want to explicitly- // drop or transform, passthrough the rest unchanged in the return value.- //- // See: [Note: Use looseObject when parsing JSON that will get persisted].- const {- owner,- encryptedKey,- keyDecryptionNonce,- encryptedName,- nameDecryptionNonce,- sharees,- attributes,- isDeleted,- magicMetadata: encryptedMagicMetadata,- pubMagicMetadata: encryptedPubMagicMetadata,- sharedMagicMetadata: encryptedSharedMagicMetadata,- ...rest- } = collection;-- // We've already used them to derive the `collectionKey`.- ignore([encryptedKey, keyDecryptionNonce]);- // Mobile specific attribute not currently used by us.- ignore(attributes);- // The deleted flag is used during collection fetch, but not used by us- // beyond this point.- ignore(isDeleted);-- const name =- // `||` is used because remote sets name to blank to indicate absence.- collection.name ||- new TextDecoder().decode(- await decryptBoxBytes(- { encryptedData: encryptedName!, nonce: nameDecryptionNonce! },- collectionKey,- ),- );-- let magicMetadata: Collection["magicMetadata"];- if (encryptedMagicMetadata) {- const genericMM = await decryptMagicMetadata(- encryptedMagicMetadata,- collectionKey,- );- const data = CollectionPrivateMagicMetadataData.parse(genericMM.data);- magicMetadata = { ...genericMM, data };- }-- let pubMagicMetadata: Collection["pubMagicMetadata"];- if (encryptedPubMagicMetadata) {- const genericMM = await decryptMagicMetadata(- encryptedPubMagicMetadata,- collectionKey,- );- const data = CollectionPublicMagicMetadataData.parse(genericMM.data);- pubMagicMetadata = { ...genericMM, data };- }-- let sharedMagicMetadata: Collection["sharedMagicMetadata"];- if (encryptedSharedMagicMetadata) {- const genericMM = await decryptMagicMetadata(- encryptedSharedMagicMetadata,- collectionKey,- );- const data = CollectionShareeMagicMetadataData.parse(genericMM.data);- sharedMagicMetadata = { ...genericMM, data };- }-- return {- ...rest,- key: collectionKey,- owner: parseRemoteCollectionUser(owner),- name,- sharees: sharees.map(parseRemoteCollectionUser),- publicURLs: rest.publicURLs,- magicMetadata,- pubMagicMetadata,- sharedMagicMetadata,- };-};--/**- * A no-op function to pretend that we're using some values. This is handy when- * we want to destructure some fields so that they don't get forwarded, but- * otherwise don't need to use them.- */-export const ignore = (xs: unknown) => typeof xs;--/**- * A convenience function to discard the unused name field from the collection- * user objects that we receive from remote.- */-const parseRemoteCollectionUser = ({- name,- ...rest-}: RemoteCollectionUser): CollectionUser => {- ignore(name);- return rest;-};--/**- * Additional context stored as part of the collection's magic metadata to- * augment the {@link type} associated with a {@link Collection}.- */-export const CollectionSubType = {- /**- * The default / normal value. No special semantics.- */- default: 0,- /**- * The user's default hidden collection, which contains the individually- * hidden files.- */- defaultHidden: 1,- /**- * A collection created for sharing selected files.- */- quicklink: 2,-} as const;--export type CollectionSubType =- (typeof CollectionSubType)[keyof typeof CollectionSubType];--/**- * Ordering of the collection - Whether it is pinned or not.- */-export const CollectionOrder = {- /**- * The default / normal value. No special semantics, behaves "unpinned" and- * will retain its natural sort position.- */- default: 0,- /**- * The collection is "pinned" by moving to the beginning of the sort order.- *- * Multiple collections can be pinned, in which case they'll be sorted- * amongst themselves under the otherwise applicable sort order.- *- * -- [pinned collections] -- [other collections] --- */- pinned: 1,-} as const;--export type CollectionOrder =- (typeof CollectionOrder)[keyof typeof CollectionOrder];--/**- * Mutable private metadata associated with a {@link Collection}.- *- * - Unlike {@link CollectionPublicMagicMetadataData} this is only available to- * the owner of the file.- *- * See: [Note: Private magic metadata is called magic metadata on remote]- */-export interface CollectionPrivateMagicMetadataData {- /**- * The subtype of the collection type (if applicable).- *- * Expected to be one of {@link CollectionSubType}.- */- subType?: number;- /**- * The (owner specific) visibility of the collection.- *- * The file's visibility is user specific attribute, and thus we keep it in- * the private magic metadata. This allows the file's owner to share a file- * and independently edit its visibility without revealing their visibility- * preference to the other people with whom they have shared the file.- *- * Expected to be one of {@link ItemVisibility}.- *- * See: [Note: Enums in remote objects] for why we keep it as a number- * instead of the expected enum.- */- visibility?: number;- /**- * An overrride to the sort ordering used for the collection.- *- * Expected to be one of {@link CollectionOrder}.- */- order?: number;-}--/**- * Zod schema for {@link CollectionPrivateMagicMetadataData}.- *- * See: [Note: Use looseObject for metadata Zod schemas]- */-export const CollectionPrivateMagicMetadataData = z.looseObject({- subType: z.number().nullish().transform(nullToUndefined),- visibility: z.number().nullish().transform(nullToUndefined),- order: z.number().nullish().transform(nullToUndefined),-});--/**- * Mutable public metadata associated with a {@link Collection}.- *- * - Unlike {@link CollectionPrivateMagicMetadataData}, this is available to all- * people with whom the collection has been shared.- *- * For more details, see [Note: Metadatum].- */-export interface CollectionPublicMagicMetadataData {- /**- * The ordering of the files within the collection.- *- * The default is desc ("Newest first").- *- * If true, then the files within the collection are sorted in ascending- * order of their time ("Oldest first").- *- * To reset to the default, set this to false.- */- asc?: boolean;- /**- * The file ID of the file to use as the cover for the collection.- *- * To reset to the default cover, set this to 0.- */- coverID?: number;- /**- * The layout type for the public collection display.- *- * Expected to be one of: "masonry", "grouped", "continuous", "trip".- */- layout?: string;-}--/**- * Zod schema for {@link CollectionPublicMagicMetadataData}.- */-export const CollectionPublicMagicMetadataData = z.looseObject({- asc: z.boolean().nullish().transform(nullToUndefined),- coverID: z.number().nullish().transform(nullToUndefined),- layout: z.string().nullish().transform(nullToUndefined),-});--/**- * Per-sharee mutable metadata associated with a shared {@link Collection}.- *- * [Note: Share specific metadata]- *- * When a collection is shared with a particular user, then remote creates a new- * "share" entity defined by the (collectionID, fromUserID, toUserID) tuple- * (this entity is not exposed to us directly, but it is helpful to know the- * underlying implementation for this discussion).- *- * Remote also allows us to store mutable metadata (aka "magic metadata") with- * each such share entity. This effectively acts as a private space where each- * user with whom a collection has been shared can store and mutate metadata- * about this shared collection without affecting either the owner or other- * users with whom the collection has been shared.- */-export interface CollectionShareeMagicMetadataData {- /**- * The (sharee specific) visibility of the collection.- *- * Expected to be one of {@link ItemVisibility}.- */- visibility?: number;- /**- * An override to the sort ordering used for the collection by the sharee.- *- * Expected to be one of {@link CollectionOrder}.- */- order?: number;-}--/**- * Zod schema for {@link CollectionShareeMagicMetadataData}.- */-export const CollectionShareeMagicMetadataData = z.looseObject({- visibility: z.number().nullish().transform(nullToUndefined),- order: z.number().nullish().transform(nullToUndefined),-});diff --git a/web/apps/albums/vendor/ente-media/file-metadata.ts b/web/apps/albums/vendor/ente-media/file-metadata.tsdeleted file mode 100644index 68968317fa..0000000000--- a/web/apps/albums/vendor/ente-media/file-metadata.ts+++ /dev/null@@ -1,839 +0,0 @@-import { type Location } from "ente-base/types";-import { type EnteFile } from "ente-media/file";-import { nullToUndefined } from "ente-utils/transform";-import { z } from "zod";-import { FileType } from "./file-type";--/**- * Information about the file that never changes post upload.- *- * ---- *- * [Note: Metadatum]- *- * There are three different sources of metadata relating to a file.- *- * 1. Metadata- * 2. Magic metadata- * 3. Public magic metadata- *- * The names of API entities are such for historical reasons, but we can think- * of them as:- *- * 1. Metadata- * 2. Private mutable metadata- * 3. Public mutable metadata- *- * Metadata is the original metadata that we attached to the file when it was- * uploaded. It is immutable, and it never changes.- *- * Later on, the user might make changes to the file's metadata. Since the- * metadata is immutable, we need a place to keep these mutations.- *- * Some mutations are "private" to the user who owns the file. For example, the- * user might archive the file. Such modifications get written to (2), Private- * Mutable Metadata.- *- * Other mutations are "public" across all the users with whom the file is- * shared. For example, if the user (owner) edits the name of the file, all- * people with whom this file is shared can see the new edited name. Such- * modifications get written to (3), Shared Mutable Metadata.- *- * When the client needs to show a file, it needs to "merge" in two or three of- * these sources (nb: remote will only send the permissible ones):- *- * - When showing a shared file, (1) and (3) are merged, with changes from (3)- * taking precedence, to obtain the full metadata pertinent to the file.- *- * - When showing a normal (un-shared) file, (1), (2) and (3) are merged, with- * changes from (2) and (3) taking precedence, to obtain the full metadata.- * (2) and (3) have no intersection of keys, so they can be merged in any- * order.- *- * While these sources can be conceptually merged, it is important for the- * client to also retain the original sources unchanged. This is because the- * metadatas (any of the three) might have keys that the current client does not- * yet understand, so when updating some key, say filename in (3), it should- * only edit the key it knows about but retain the rest of the source JSON- * unchanged.- *- * A similar concept applies to collections, which can (like files) have- * metadata associated with them with varying axis of mutability and access.- *- * Collections also have another type of metadata.- *- * 4. Shared magic metadata- *- * which in our hypothetical naming scheme can be thought of as- *- * 4. Per-sharee private mutable metadata- *- * This is "magic metadata" associated with each share. Each user with whom the- * collection has been shared with can use it store metadata (e.g. archive- * status) that is private to them, and can only be edited by them. For more- * details on this type of metadata, see [Note: Share specific metadata].- */-export interface FileMetadata {- /**- * The "Ente" file type - image, video or live photo.- *- * Expected to be one of {@link FileType}.- *- * See: [Note: Enums in remote objects] for why we keep it as a number- * instead of the expected enum.- */- fileType: number;- /**- * The name of the file (including its extension).- *- * Don't use this property directly, use {@link fileFileName} instead which- * takes into account subsequent edits too.- */- title: string;- /**- * The time when this file was created (epoch microseconds).- *- * This is our best attempt at detecting the time when the photo or live- * photo or video was taken.- *- * - We first try to obtain this from metadata, using Exif and other- * metadata for images and FFmpeg-extracted metadata for video.- *- * - If no suitable metadata is available, then we try to deduce it from- * file name (e.g. for screenshots without any embedded metadata).- *- * - If nothing can be found, then it is set to the current time at the time- * of the upload.- */- creationTime: number;- /**- * The last modification time of the file (epoch microseconds).- */- modificationTime: number;- /**- * The latitude where the file was taken.- */- latitude?: number;- /**- * The longitude where the file was taken.- */- longitude?: number;- /**- * A hash of the file's contents.- *- * For images and videos this is the hash of the file's contents. For live- * photos, this is the image hash joined with video hash using a colon (i.e.- * `${imageHash}:{videoHash}`).- *- * Legacy compatibility:- *- * - The hash might not be present for files uploaded from ancient versions- * of Ente (Newer clients will always include it in the metadata).- *- * - For live photos, older version of the web and desktop client used to- * add two separate fields - {@link imageHash} and {@link videoHash} - to- * the file's metadata instead of setting the {@link hash}. This behaviour- * is deprecated, and if we now see a live photo without a {@link hash},- * we should reconstruct the hash locally from the image and video hashes- * by combining them as `${imageHash}:{videoHash}`.- */- hash?: string;- /**- * The hash of the image component of a live photo.- *- * This is a legacy field, and should not be added by us anymore. It is- * retained to allow us to reconstruct the hash for live photos uploaded by- * older clients.- */- imageHash?: string;- /**- * The hash of the video component of a live photo.- *- * This is a legacy field, and should not be added by us anymore. It is- * retained to allow us to reconstruct the hash for live photos uploaded by- * older clients.- */- videoHash?: string;- /**- * The duration (in integral seconds) of the video.- *- * Only present for videos (`fileType == FileType.video`). For compatibility- * with other clients, this must be a integer number of seconds, without any- * sub-second fraction.- */- duration?: number;- /**- * `true` if the uploading client was unable to generate a thumbnail for the- * file when uploading it (e.g. unsupported format), and so instead a- * placeholder thumbnail was used.- */- hasStaticThumbnail?: boolean;-}--/**- * Zod schema for {@link FileMetadata}.- */-export const FileMetadata = z.looseObject({- fileType: z.number(),- title: z.string(),- creationTime: z.number(),- modificationTime: z.number(),- latitude: z.number().nullish().transform(nullToUndefined),- longitude: z.number().nullish().transform(nullToUndefined),- hash: z.string().nullish().transform(nullToUndefined),- imageHash: z.string().nullish().transform(nullToUndefined),- videoHash: z.string().nullish().transform(nullToUndefined),- duration: z.number().nullish().transform(nullToUndefined),- hasStaticThumbnail: z.boolean().nullish().transform(nullToUndefined),-});--/**- * Mutable private metadata associated with an {@link EnteFile}.- *- * - Unlike {@link FileMetadata}, this can change after the file has been- * uploaded.- *- * - Unlike {@link PublicMagicMetadata}, this is only available to the owner of- * the file.- *- * [Note: Private magic metadata is called magic metadata on remote]- *- * For historical reasons, the unqualified phrase "magic metadata" in various- * APIs refers to the (this) private metadata, even though the mutable public- * metadata is the much more frequently used of the two. See: [Note: Metadatum].- */-export interface FilePrivateMagicMetadataData {- /**- * The visibility of the file.- *- * The file's visibility is user specific attribute, and thus we keep it in- * the private magic metadata. This allows the file's owner to share a file- * and independently edit its visibility without revealing their visibility- * preference to the other people with whom they have shared the file.- *- * Expected to be one of {@link ItemVisibility}.- */- visibility?: number;-}--/**- * Zod schema for {@link FilePrivateMagicMetadataData}.- *- * See: [Note: Use looseObject for metadata Zod schemas]- */-export const FilePrivateMagicMetadataData = z.looseObject({- visibility: z.number().nullish().transform(nullToUndefined),-});--/**- * The visibility of an Ente file or collection.- */-export const ItemVisibility = {- /**- * The normal state - The item is visible.- */- visible: 0,- /**- * The item has been archived.- */- archived: 1,- /**- * The item has been hidden.- */- hidden: 2,-} as const;--/**- * The visibility of an Ente file or collection.- *- * This is the erasable type. See the {@link ItemVisibility} object for the- * possible values and their symbolic constants.- */-export type ItemVisibility =- (typeof ItemVisibility)[keyof typeof ItemVisibility];--/**- * Mutable public metadata associated with an {@link EnteFile}.- *- * - Unlike {@link FileMetadata}, this can change after the file has been- * uploaded.- *- * - Unlike {@link FilePrivateMagicMetadataData}, this is available to all the- * people with whom the file has been shared.- *- * For more details, see [Note: Metadatum].- *- * ---- *- * [Note: Optional magic metadata keys]- *- * Remote does not support nullish (`undefined` or `null`) values for the keys- * in the magic metadata associated with a file. All of the keys themselves are- * optional though.- *- * That is, all magic metadata properties are of the form:- *- * foo?: T- *- * And never like:- *- * foo: T | undefined- */-export interface FilePublicMagicMetadataData {- /**- * A ISO 8601 date time string without a timezone, indicating the local time- * where the photo (or video) was taken.- *- * e.g. "2022-01-26T13:08:20".- *- * See: [Note: Photos are always in local date/time].- */- dateTime?: string;- /**- * When available, a "±HH:mm" string indicating the UTC offset of the place- * where the photo was taken.- *- * e.g. "+02:00".- */- offsetTime?: string;- /**- * Modified value of the date time associated with an {@link EnteFile}.- *- * Epoch microseconds.- *- * This field stores edits to the {@link creationTime} {@link FileMetadata}- * field.- */- editedTime?: number;- /**- * Modified file name of the {@link EnteFile}.- *- * This field stores edits to the {@link title} {@link FileMetadata} field.- */- editedName?: string;- /**- * The width of the photo (or video) in pixels.- *- * While this should usually be present, it is not guaranteed to be.- */- w?: number;- /**- * The height of the photo (or video) in pixels, if available.- *- * While this should usually be present, it is not guaranteed to be.- */- h?: number;- /**- * An arbitrary caption / description string that the user has added to the- * file.- *- * The length of this field is capped to some arbitrary maximum by client- * side checks.- */- caption?: string;- /**- * The name provided by the person who uploaded the file using an otherwise- * anonymous public link upload.- *- * When sharing an album using a public link, the owner of the collection- * can enable public uploads. When uploading files this way, the public- * albums app asks the person doing the upload their name, and that gets- * persisted here in the file's public magic metadata so that it can be- * shown to the Ente users who are participants in the collection.- *- * (The owner of such files will be the owner of the collection)- */- uploaderName?: string;- /** Camera make (manufacturer) extracted from metadata. */- cameraMake?: string;- /** Camera model extracted from metadata. */- cameraModel?: string;- /**- * Edited latitude of the file- *- * If the user edits the location (latitude and longitude) of a file within- * Ente, then the edits will be stored as the {@link lat} and {@link long}- * properties in the file's public magic metadata.- */- lat?: number;- /**- * Edited longitude of the file.- *- * See {@link long}.- */- long?: number;- /**- * An arbitrary integer set to indicate that this file should be skipped for- * the purpose of HLS generation.- *- * Current semantics:- *- * - if 1, skip this file- * - otherwise attempt processing- *- * [Note: Marking files which do not need video processing]- *- * Some video files do not require generation of a HLS stream. The current- * logic is H.264 files less than 10 MB, but this might change in future- * clients.- *- * For such skipped files, there thus won't be a HLS playlist generated.- * However, we still need a way to indicate to other clients that this file- * has already been looked at.- *- * To that end, we add a flag to the public magic metadata for the file. To- * allow future flexibility, this flag is an integer "streaming version".- * Currently it is set to 1 by a client who recognizes that this file does- * not need processing, and other clients can ignore this file if they find- * sv == 1. In the future, there might be other values for sv (e.g. if the- * skip logic changes).- */- sv?: number;-}--/**- * Zod schema for the {@link PublicMagicMetadata} type.- *- * [Note: Use looseObject for metadata Zod schemas]- *- * It is important to (recursively) use the {@link looseObject} option when- * defining Zod schemas for the various metadata types (the plaintext JSON- * objects) because we want to retain all the fields we get from remote. There- * might be other, newer, clients out there adding fields that the current- * client might not we aware of, and we don't want to overwrite them.- */-export const FilePublicMagicMetadataData = z.looseObject({- dateTime: z.string().nullish().transform(nullToUndefined),- offsetTime: z.string().nullish().transform(nullToUndefined),- editedTime: z.number().nullish().transform(nullToUndefined),- editedName: z.string().nullish().transform(nullToUndefined),- w: z.number().nullish().transform(nullToUndefined),- h: z.number().nullish().transform(nullToUndefined),- // Some legacy remote records have been seen with numeric captions.- caption: z- .union([z.string(), z.number()])- .nullish()- .transform((v) => (v == null ? undefined : String(v))),- uploaderName: z.string().nullish().transform(nullToUndefined),- cameraMake: z.string().nullish().transform(nullToUndefined),- cameraModel: z.string().nullish().transform(nullToUndefined),- lat: z.number().nullish().transform(nullToUndefined),- long: z.number().nullish().transform(nullToUndefined),- sv: z.number().nullish().transform(nullToUndefined),-});--/**- * Return the hash of the file by reading it from its metadata.- *- * This is a convenience function that directly reads the information from the- * metadata in the happy path, but also has branches to handle the legacy format- * that older clients used to upload. For more details, see the note in the- * documentation for {@link hash} in {@link FileMetadata}.- */-export const metadataHash = (metadata: FileMetadata) => {- const hash = metadata.hash;- if (hash) return hash;-- // Handle past live photos upload from web client.- if (- metadata.fileType == FileType.livePhoto &&- metadata.imageHash &&- metadata.videoHash- ) {- return `${metadata.imageHash}:${metadata.videoHash}`;- }-- // Items uploaded by very old clients might not have a hash, so this is not- // necessarily an error even if rare.- return undefined;-};--/**- * Return `true` if the {@link ItemVisibility} of the given {@link file} is- * archived.- */-export const isArchivedFile = (file: EnteFile) =>- file.magicMetadata?.data.visibility == ItemVisibility.archived;--/**- * Return the file name of the file (including both the name and the extension).- *- * This function handles files with edited names. It will first look into the- * public magic metadata of a file to see if the file has an edited name, and if- * so, return that. Otherwise it will return the original name of the file- * stored in its metadata.- *- * @returns The provided {@link EnteFile}'s filename, including the extension.- * e.g. "flower.png".- */-export const fileFileName = (file: EnteFile) =>- file.pubMagicMetadata?.data.editedName ?? file.metadata.title;--/**- * Return the file's creation timestamp (epoch microseconds).- *- * This function handles files with edited dates.- *- * While sometimes the epoch timestamp is the correct value to use, it is also- * possible that {@link fileCreationPhotoDate} might be more appropriate.- */-export const fileCreationTime = (file: EnteFile) =>- file.pubMagicMetadata?.data.editedTime ?? file.metadata.creationTime;--/**- * Return the file's creation date as a Date in the hypothetical "timezone of- * the photo".- *- * This function handles files with edited dates. For all the details and- * nuance, see {@link createPhotoDate}.- */-export const fileCreationPhotoDate = (file: EnteFile) =>- createPhotoDate(- file.pubMagicMetadata?.data.dateTime ??- file.pubMagicMetadata?.data.editedTime ??- file.metadata.creationTime,- );--/**- * Return the GPS coordinates (if any) present in the given {@link EnteFile}.- *- * This function handles files with edited locations.- */-export const fileLocation = (file: EnteFile): Location | undefined => {- const { lat, long } = file.pubMagicMetadata?.data ?? {};- // Use (lat, long) only if both are present and nonzero.- const edited = lat && long;-- const latitude = nullToUndefined(edited ? lat : file.metadata.latitude);- const longitude = nullToUndefined(edited ? long : file.metadata.longitude);-- if (latitude === undefined || longitude === undefined) return undefined;- if (Number.isNaN(latitude) || Number.isNaN(longitude)) return undefined;- if (latitude === 0 && longitude === 0) return undefined;-- return { latitude, longitude };-};--/**- * Return the camera make (manufacturer) for the file.- */-export const fileCameraMake = (file: EnteFile): string | undefined => {- const rawMake = file.pubMagicMetadata?.data.cameraMake;- if (!rawMake) return undefined;- const make = rawMake.trim();- if (make.length === 0) return undefined;- return make;-};--/**- * Return the camera model for the file.- */-export const fileCameraModel = (file: EnteFile): string | undefined => {- const rawModel = file.pubMagicMetadata?.data.cameraModel;- if (!rawModel) return undefined;- const model = rawModel.trim();- if (model.length === 0) return undefined;- return model;-};--/**- * Return a user-friendly string describing the camera used for the file.- */-export const fileCameraLabel = (file: EnteFile): string | undefined => {- const make = fileCameraMake(file);- const model = fileCameraModel(file);- if (!make && !model) return undefined;- if (make && model) return `${make} ${model}`;- return model ?? make;-};--/**- * Return the duration of the video as a formatted "HH:mm:ss" string (when- * present) for the given {@link EnteFile}.- *- * Only files with type `FileType.video` are expected to have a duration.- *- * @returns The duration of the video as a string of the form "HH:mm:ss". The- * underlying duration present in the file's metadata is guaranteed to be- * integral, so there will never be a subsecond component.- *- * - If the hour component is all zeroes, it will be omitted.- *- * - Leading zeros in the minutes component will be trimmed off if an hour- * component is not present. If minutes is all zeros, then "0" will be used.- *- * - For example, an underlying duration of 595 seconds will result in a- * formatted string of the form "9:55". While an underlying duration of 9- * seconds will be returned as a string "0:09".- *- * - A zero duration will be treated as undefined.- */-export const fileDurationString = (file: EnteFile): string | undefined => {- const d = file.metadata.duration;- if (!d) return undefined;-- const s = d % 60;- const m = Math.floor(d / 60) % 60;- const h = Math.floor(d / 3600);-- const ss = s > 9 ? `${s}` : `0${s}`;- if (h) {- const mm = m > 9 ? `${m}` : `0${m}`;- return `${h}:${mm}:${ss}`;- } else {- return `${m}:${ss}`;- }-};--/**- * Metadata about a file extracted from various sources (like Exif) when- * uploading it into Ente.- *- * Depending on the file type and the upload sequence, this data can come from- * various places:- *- * - For images it comes from the Exif and other forms of metadata (XMP, IPTC)- * embedded in the file.- *- * - For videos, similarly it is extracted from the metadata embedded in the- * file using ffmpeg.- *- * - From various sidecar files (like metadata JSONs) that might be sitting next- * to the original during an import.- *- * These bits then get distributed and saved in the various metadata fields- * associated with an {@link EnteFile} (See: [Note: Metadatum]).- *- * The advantage of having them be attached to an {@link EnteFile} is that it- * allows us to perform operations using these attributes without needing to- * re-download the original image.- *- * The disadvantage is that it increases the network payload (anything attached- * to an {@link EnteFile} comes back in the diff response), and thus latency and- * local storage costs for all clients. Thus, we need to curate what gets- * preserved within the {@link EnteFile}'s metadatum.- */-export interface ParsedMetadata {- /** The width of the image, in pixels. */- width?: number;- /** The height of the image, in pixels. */- height?: number;- /**- * The date/time when this photo was taken.- *- * Logically this is a date in local timezone of the place where the photo- * was taken. See: [Note: Photos are always in local date/time].- */- creationDate?: ParsedMetadataDate | undefined;- /** The GPS coordinates where the photo was taken. */- location?: Location;- /**- * A caption / description attached by the user to the photo.- */- description?: string;- /** Camera make (manufacturer) extracted from metadata (e.g. Apple, Canon). */- cameraMake?: string;- /** Camera model extracted from metadata (e.g. iPhone 15 Pro). */- cameraModel?: string;-}--/**- * [Note: Photos are always in local date/time]- *- * Photos out in the wild frequently do not have associated timezone offsets for- * the date/time embedded in their metadata. This is a artifact of an era where- * cameras didn't know often even know their date/time correctly, let alone the- * UTC offset of their local data/time.- *- * This is beginning to change with smartphone cameras, and is even reflected in- * the standards. e.g. Exif metadata now has auxiliary "OffsetTime*" tags for- * indicating the UTC offset of the local date/time in the existing Exif tags- * (See: [Note: Exif dates]).- *- * So a photos app needs to deal with a mixture of photos whose dates may or may- * not have UTC offsets. This is fact #1.- *- * Users expect to see the time they took the photo, not the time in the place- * they are currently. People expect a New Year's Eve photo from a vacation to- * show up as midnight, not as (e.g.) 19:30 IST. This is fact #2.- *- * Combine these two facts, and if you ponder a bit, you'll find that there is- * only one way for a photos app to show / sort / label the date – by using the- * local date/time without the attached UTC offset, **even if it is present**.- *- * The UTC offset is still useful though, and we don't want to lose that- * information. The number of photos with a UTC offset will only increase. And- * whenever it is present, it provides additional context for the user.- *- * So we keep both the local date/time string (an ISO 8601 string guaranteed to- * be without an associated UTC offset), and an (optional) UTC offset string.- *- * It is important to NOT think of the local date/time string as an instant of- * time that can be converted to a UTC timestamp. It cannot be converted to a- * UTC timestamp because while it itself might have the optional associated UTC- * offset, its siblings photos might not. The only way to retain their- * comparability is to treat them all the "time zone where the photo was taken".- *- * All this is good, but we still need to retain the existing `creationTime` UTC- * epoch timestamp because in some cases when importing photos from other- * providers, that's all we get. We could try and convert that to a date/time- * string too, but since we anyways need to handle existing code that deals with- * epoch timestamps, we retain them as they were provided.- */-export interface ParsedMetadataDate {- /**- * A local date/time.- *- * This is a partial ISO 8601 date/time string guaranteed not to have a- * timezone offset. e.g. "2023-08-23T18:03:00.000".- */- dateTime: string;- /**- * An optional offset from UTC.- *- * This is an optional UTC offset string of the form "±HH:mm" or "Z",- * specifying the timezone offset for {@link dateTime} when available.- */- offset: string | undefined;- /**- * UTC epoch microseconds derived from {@link dateTime} and- * {@link offset}.- *- * When the {@link offset} is present, this will accurately reflect a- * UTC timestamp. When the {@link offset} is not present it convert to a- * UTC timestamp by assuming that the given {@link dateTime} is in the local- * time where this code is running. This is a good assumption but not always- * correct (e.g. vacation photos).- */- timestamp: number;-}--/**- * Parse a partial or full ISO 8601 string into a {@link ParsedMetadataDate}.- *- * @param s A partial or full ISO 8601 string. That is, it is a string of the- * form "2023-08-23T18:03:00.000+05:30" or "2023-08-23T12:33:00.000Z" with all- * components except the year potentially missing.- *- * @return A {@link ParsedMetadataDate}, or `undefined` if {@link s} cannot be- * parsed.- *- * ---- * Some examples:- *- * - "2023" => ("2023-01-01T00:00:00.000", undefined)- * - "2023-08" => ("2023-08-01T00:00:00.000", undefined)- * - "2023-08-23" => ("2023-08-23T00:00:00.000", undefined)- * - "2023-08-23T18:03:00" => ("2023-08-23T18:03:00.000", undefined)- * - "2023-08-23T18:03:00+05:30" => ("2023-08-23T18:03:00.000', "+05:30")- * - "2023-08-23T18:03:00.000+05:30" => ("2023-08-23T18:03:00.000", "+05:30")- * - "2023-08-23T12:33:00.000Z" => ("2023-08-23T12:33:00.000", "Z")- */-export const parseMetadataDate = (- s: string,-): ParsedMetadataDate | undefined => {- // Construct the timestamp using the original string itself. If s is- // parseable as a date, then this'll be give us the correct UTC timestamp.- // If the UTC offset is not present, then this will be in the local- // (current) time.- const timestamp = new Date(s).getTime() * 1000;- if (isNaN(timestamp)) {- // s in not a well formed ISO 8601 date time string.- return undefined;- }-- // Now we try to massage s into two parts - the local date/time string, and- // an UTC offset string.-- let offset: string | undefined;- let sWithoutOffset: string;-- // Check to see if there is a time-zone descriptor of the form "Z" or- // "±05:30" or "±0530" at the end of s.- const m = /Z|[+-]\d\d:?\d\d$/.exec(s);- if (m?.index) {- sWithoutOffset = s.substring(0, m.index);- offset = s.substring(m.index);- } else {- sWithoutOffset = s;- }-- // Convert sWithoutOffset - a potentially partial ISO 8601 string - to a- // canonical ISO 8601 string.- //- // In its full generality, this is non-trivial. The approach we take is:- //- // 1. Rely on the browser to be able to partial ISO 8601 string. This relies- // on non-standard behaviour but works in practice seemingly.- //- // 2. Get an ISO 8601 representation of it. This is standard.- //- // A thing to watch out for is that browsers treat date only and date time- // strings differently when the offset is not present (as would be for us).- //- // > When the time zone offset is absent, date-only forms are interpreted as- // > a UTC time and date-time forms are interpreted as local time.- // >- // > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format- //- // For our purpose, we want to always interpret them as UTC time. This way,- // when we later gets back its string representation for step 2, we will get- // back the same numerical value, and can just chop off the "Z".- //- // So if the length of the string is less than or equal to yyyy-mm-dd (10),- // then we use it verbatim, otherwise we append a "Z".-- const date = new Date(- sWithoutOffset + (sWithoutOffset.length <= 10 ? "" : "Z"),- );-- // The string returned by `toISOString` is guaranteed to be UTC and denoted- // by the suffix "Z". If we chop that off, we get back a canonical- // representation we wish for: A otherwise well-formed ISO 9601 string but- // any time zone descriptor.- const dateTime = dropLast(date.toISOString());-- return { dateTime, offset, timestamp };-};--const dropLast = (s: string) => (s ? s.substring(0, s.length - 1) : s);--/**- * Return a date that can be used on the represent a photo on the UI, by- * constructing it from a {@link ParsedMetadataDate}, or its {@link dateTime}- * component, or a UTC epoch timestamp.- *- * These dates are all hypothetically in the timezone of the place where the- * photo was taken. Different photos might've been taken in different timezones,- * which is why it is hypothetical, so concretely these are all mapped to the- * current timezone.- *- * The difference is subtle, but we should not think of these as absolute points- * on the UTC timeline. They are instead better thought of as dates without an- * associated timezone. For the purpose of mapping them all to a comparable- * dimension them we all contingently use the current timezone - this makes it- * easy to use JavaScript Date constructor which assumes that any date/time- * string without an associated timezone is in the current timezone.- *- * Whenever we're surfacing them in the UI, or using them for grouping (say by- * day), we should use their current timezone representation, not the UTC one.- *- * See also: [Note: Photos are always in local date/time].- */-export const createPhotoDate = (- dateLike: ParsedMetadataDate | string | number,-) => {- switch (typeof dateLike) {- case "object":- // A ISO 8601 string without a timezone. The Date constructor will- // assume the timezone to be the current timezone.- return new Date(dateLike.dateTime);- case "string":- // This is expected to be a string with the same meaning as- // `ParsedMetadataDate.dateTime`.- return new Date(dateLike);- case "number":- // A UTC epoch microseconds value.- return new Date(dateLike / 1000);- }-};diff --git a/web/apps/albums/vendor/ente-media/file-type.ts b/web/apps/albums/vendor/ente-media/file-type.tsdeleted file mode 100644index c0deee74bb..0000000000--- a/web/apps/albums/vendor/ente-media/file-type.ts+++ /dev/null@@ -1,75 +0,0 @@-/**- * The type of an {@link EnteFile}.- *- * This is an object containing symbolic constant. There is also an eraseable- * TypeScript type type with the same name, {@link FileType}.- */-export const FileType = {- /**- * An image (e.g. JPEG).- */- image: 0,- /**- * A video (e.g. MP4).- */- video: 1,- /**- * A live photo, aka motion photo.- *- * This is a combination of an image and a (short) video capturing the- * before and after when the image was taken. We preserve it as a zip- * containing both the parts.- */- livePhoto: 2,-} as const;--/**- * The type of an {@link EnteFile}.- *- * This is an eraseable TypeScript type. There is also a {@link FileType} object- * with the same name that contains the corresponding symbolic constants.- */-export type FileType = (typeof FileType)[keyof typeof FileType];--export interface FileTypeInfo {- fileType: FileType;- /**- * A lowercased, standardized extension for files of the current type.- *- * For live photos, this is set to the extension of the image component of- * the live photo.- */- extension: string;- mimeType?: string;-}--// list of format that were missed by type-detection for some files.-export const KnownFileTypeInfos: FileTypeInfo[] = [- { fileType: FileType.image, extension: "jpeg", mimeType: "image/jpeg" },- { fileType: FileType.image, extension: "jpg", mimeType: "image/jpeg" },- { fileType: FileType.video, extension: "webm", mimeType: "video/webm" },- { fileType: FileType.video, extension: "mod", mimeType: "video/mpeg" },- { fileType: FileType.video, extension: "mp4", mimeType: "video/mp4" },- { fileType: FileType.image, extension: "gif", mimeType: "image/gif" },- { fileType: FileType.video, extension: "dv", mimeType: "video/x-dv" },- { fileType: FileType.video, extension: "wmv", mimeType: "video/x-ms-asf" },- { fileType: FileType.video, extension: "hevc", mimeType: "video/hevc" },- {- fileType: FileType.image,- extension: "raf",- mimeType: "image/x-fuji-raf",- },- {- fileType: FileType.image,- extension: "orf",- mimeType: "image/x-olympus-orf",- },- {- fileType: FileType.image,- extension: "crw",- mimeType: "image/x-canon-crw",- },- { fileType: FileType.video, extension: "mov", mimeType: "video/quicktime" },-];--export const KnownNonMediaFileExtensions = ["xmp", "html", "txt"];diff --git a/web/apps/albums/vendor/ente-media/file.ts b/web/apps/albums/vendor/ente-media/file.tsdeleted file mode 100644index 04f2e004c7..0000000000--- a/web/apps/albums/vendor/ente-media/file.ts+++ /dev/null@@ -1,473 +0,0 @@-import { decryptBox, decryptMetadataJSON } from "ente-base/crypto";-import log from "ente-base/log";-import { nullishToBlank, nullToUndefined } from "ente-utils/transform";-import { z } from "zod";-import { ignore } from "./collection";-import {- fileFileName,- FileMetadata,- FilePrivateMagicMetadataData,- FilePublicMagicMetadataData,-} from "./file-metadata";-import { FileType } from "./file-type";-import {- decryptMagicMetadata,- RemoteMagicMetadata,- type MagicMetadata,-} from "./magic-metadata";--/**- * A File.- *- * An EnteFile represents a file in Ente. It does not contain the actual data.- *- * It is named with an "Ente" prefix to disambiguate it from the web's native- * {@link File} type.- *- * All files have an id (numeric) that is unique across all the files stored by- * an Ente instance. Each file is also always associated with a collection, and- * has an owner (both of these linkages are stored as the corresponding numeric- * IDs within the EnteFile structure).- *- * > For shared files, the owner of the file is not necessarily the owner of all- * > the collections to which the file belongs.- *- * While the file ID is unique, we'd can still have multiple entries for each- * file ID in our local state, one for each {@link Collection} to which the file- * belongs. That is, the uniqueness is across the (fileID, collectionID) pairs.- * See [Note: Collection file].- *- * [Note: File lifecycle]- *- * 1. **Normal**: A file starts off by belonging to at least one collection. It- * can then be added to additional collections, each of which will be an- * EnteFile with a distinct (fileID, collectionID) pair.- *- * 2. **Trash**: If the user deletes the file, then the file moves to trash.- * Such files will have {@link isDeleted} `true` in their- * {@link RemoteEnteFile} entries when we perform a collection diff to let- * the client know that the corresponding file is no longer part of the- * collection.- *- * Such files will now be returned as part of the trash diff, with both- * {@link isDeleted} and {@link isRestored} set to `false` for their trash- * entry.- *- * 3. **Restore**: If the the user were to restore the file before permanent- * deletion, then it effectively works as moving a normal file to an normal- * collection. In particular, if we were to restore the file back to one of- * the collections it was part of pre-trash, and then fetch the collection- * diff for that collection, we would get back the same file object, except- * with {@link isDeleted} will now be `false`.- *- * The trash entry for restored files will have {@link isRestored} set to- * `true` to notify clients that an item that was previously in trash is no- * longer there because it has been restored.- *- * 4. **Permanent deletion**: If the file remains in trash for 30 days, or if- * the user explictly permanently deletes it from the trash, or if the user- * explicitly clears the trash, then it will get permanently deleted.- *- * The trash entry for such permanently deleted files will have- * {@link isDeleted} set to `true` to notify clients that an item that was- * previously in trash is no longer there because it has been permanently- * deleted.- *- * When a file is permanently deleted, remote will scrub off data from its- * fields. See: [Note: Optionality of remote file fields].- */-export interface EnteFile {- /**- * The file's globally unique ID.- *- * The file's ID is a integer assigned by remote as the identifier for an- * {@link EnteFile} when it is created. It is globally unique across all- * files stored by an Ente instance, and is not scoped to the current user.- */- id: number;- /**- * The ID of the collection with which this file as associated.- *- * The same file (ID) may be associated with multiple collectionID, each of- * which will come and stay as distinct {@link EnteFile} instances - all of- * which will have the same {@link id} but distinct {@link collectionID}.- *- * So the ({@link id}, {@link collectionID}) pair is a primary key, not the- * {@link id} on its own. See: [Note: Collection file].- */- collectionID: number;- /**- * The ID of the Ente user who owns the file.- *- * Files uploaded by non users on public links belong to the owner of the- * collection who created the public link (See {@link uploaderName} in- * {@link FilePublicMagicMetadataData}).- */- ownerID: number;- /**- * The file's key.- *- * This is the base64 representation of the decrypted encryption key- * associated with this file. When we get the file from remote (as a- * {@link RemoteEnteFile}), the file key itself would have been encrypted by- * the key of the {@link Collection} to which this file belongs.- *- * This key is used to encrypt both the file's contents, and any associated- * data (e.g., metadatum, thumbnail) for the file.- */- key: string;- /**- * Information pertaining to the encrypted S3 object that has the file's- * contents.- */- file: FileObjectAttributes;- /**- * Information pertaining to the encrypted S3 object that has the contents- * of the file's thumbnail.- */- thumbnail: FileObjectAttributes;- /**- * Static, remote visible, information associated with a file.- *- * This is information about storage used by the file and its thumbnail.- * Unlike {@link metadata} which is E2EE, the {@link FileInfo} is remote- * visible for bookkeeping purposes.- *- * Files uploaded by very old versions of Ente might not have this field.- */- info?: FileInfo;- /**- * The last time the file was updated (epoch microseconds).- *- * (e.g. magic metadata updates).- */- updationTime: number;- /**- * Public static metadata associated with a file.- *- * This is the immutable metadata that gets associated with a file when it- * is uploaded, and there after cannot be changed.- *- * It is visible to all users with whom the file gets shared.- *- * > {@link pubMagicMetadata} contains fields that override fields present- * > in the metadata. Clients overlay those atop the metadata fields, and- * > thus they can be used to implement edits.- *- * See: [Note: Metadatum].- */- metadata: FileMetadata;- /**- * Private mutable metadata associated with the file that is only visible to- * the owner of the file.- *- * See: [Note: Metadatum]- */- magicMetadata?: MagicMetadata<FilePrivateMagicMetadataData>;- /**- * Public mutable metadata associated with the file that is visible to all- * users with whom the file has been shared.- *- * While in almost all cases, files will have associated public magic- * metadata since newer clients have something or the other they need to add- * to it, its presence is not guaranteed.- *- * See: [Note: Metadatum]- */- pubMagicMetadata?: MagicMetadata<FilePublicMagicMetadataData>;-}--/**- * Attributes about an object related to an {@link EnteFile}.- *- * - The file's contents,- *- * - The file's thumbnail's contents.- */-export interface FileObjectAttributes {- /**- * The decryption header that was used when encrypting the objects's- * contents (with the file's key) before uploading them to S3 remote.- */- decryptionHeader: string;-}--export const RemoteFileObjectAttributes = z.looseObject({- /**- * The decryption header (base64 string) used when encrypting the object.- *- * For permanently deleted files, this will still be present, but remote may- * scrub it to a blank string or a placeholder.- */- decryptionHeader: z.string(),-});--/**- * Static information associated with a file.- */-export interface FileInfo {- /**- * The size of the file (in bytes).- *- * This will not be present for files with zero length.- */- fileSize?: number;- /**- * The size of the thumbnail associated with the file (in bytes).- *- * This will not be present for files that don't have thumbnails (an old Locker issue)- */- thumbSize?: number;-}--export const RemoteFileInfo = z.looseObject({- fileSize: z.number().nullish().transform(nullToUndefined),- thumbSize: z.number().nullish().transform(nullToUndefined),-});--const RemoteFileMetadata = z.object({- /**- * The metadata JSON object associated with the file, encrypted using the- * file's key.- *- * Base64 encoded.- *- * There is one case when this will be not be present - for permanently- * deleted files when we get them as part of a trash diff (see the longer- * note about this below):- *- * [Note: Optionality of remote file fields]- *- * When a file is permanently deleted, remote will scrub off data from its- * fields (either by nulling them outright, or inserting placeholders,- * depending on the remote schema).- *- * So a {@link RemoteEnteFile} object present in the trash item of a- * permanently deleted file in the trash diff response (i.e. a trash item- * with {@link isDeleted} is set to `true`) may not have the fields which we- * normally would expect to always be there for files.- *- * This is not a problem in code flow since the client will not even attempt- * to decrypt or use such file entries, so the absence of these fields has- * no impact. However, it does impact JSON validation, which might- * preemptively (and unnecessarily) fail for such {@link RemoteEnteFile}s.- *- * Luckily, this is simple to handle since most of the data in a- * {@link RemoteEnteFile} is already optional. The only tweak we require is- * handling missing {@link encryptedData} of the {@link RemoteEnteFile}'s- * {@link metadata} field in such cases. We could mark it as a optional too,- * but since we anyways shouldn't be using this field, so for convenience of- * the upstream types, we transform such missing values to a blank string.- */- encryptedData: z.string().nullish().transform(nullishToBlank),- /**- * The base64 encoded decryption header that was used during encryption of- * {@link encryptedData}.- *- * For permanently deleted files, this will still be present, but remote may- * scrub it to a blank string or a placeholder.- */- decryptionHeader: z.string(),-});--export type RemoteFileMetadata = z.infer<typeof RemoteFileMetadata>;--/**- * Zod schema for a {@link EnteFile} as represented in our interactions with- * remote.- *- * The contents of the fields are encrypted by the file's key (which itself is- * encrypted by the key of the collection that contains the file). EnteFile is- * the decrypted local representation.- *- * See: [Note: Use looseObject when parsing JSON that will get persisted]- */-export const RemoteEnteFile = z.looseObject({- id: z.number(),- collectionID: z.number(),- ownerID: z.number(),- /**- * The file's key, encrypted using the key of the collection that contains- * the file.- *- * Base64 encoded.- */- encryptedKey: z.string(),- /**- * The nonce to use when decrypting {@link encryptedKey}.- *- * Base64 encoded.- */- keyDecryptionNonce: z.string(),- file: RemoteFileObjectAttributes,- thumbnail: RemoteFileObjectAttributes,- info: RemoteFileInfo.nullish().transform(nullToUndefined),- updationTime: z.number(),- /**- * Removal marker in diff responses.- *- * This is set to `true` in the collection diff response to indicate files- * that are no longer part of the collection.- *- * - They may have been removed from the collection.- *- * - They have been deleted (either moved to trash, or permanently deleted).- */- isDeleted: z.boolean().nullish().transform(nullToUndefined),- metadata: RemoteFileMetadata,- magicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),- pubMagicMetadata: RemoteMagicMetadata.nullish().transform(nullToUndefined),-});--export type RemoteEnteFile = z.infer<typeof RemoteEnteFile>;--/**- * Zod schema for a response for various "/diff" APIs that return changes since- * a provided timestamp.- *- * - "/collections/v2/diff"- * - "/public-collection/diff"- * - "/cast/diff"- */-export const FileDiffResponse = z.object({- /**- * A batch of changes (upserts or deletions).- *- * See also: [Note: Diff response will have at most one entry for an id].- */- diff: RemoteEnteFile.array(),- /**- * If `true`, then there are more changes that can be fetched by doing- * another of the same API call, this time passing it the latest from- * amongst the timestamps of entries in {@link diff}.- */- hasMore: z.boolean(),-});--/**- * Decrypt a remote file using the provided {@link collectionKey}.- *- * @param file The remote file to decrypt.- *- * @param collectionKey The base64 encoded key of the collection to which this- * file belongs. It is needed to decrypt the file's key (which in turn is needed- * to decrypt the file's contents and other encrypted fields).- *- * @returns A decrypted {@link EnteFile}.- */-export const decryptRemoteFile = async (- remoteFile: RemoteEnteFile,- collectionKey: string,-): Promise<EnteFile> => {- // RemoteEnteFile is a looseObject, and we want to retain that semantic for- // the parsed EnteFile. Mention all fields that we want to explicitly drop- // or transform, passthrough the rest unchanged in the return value.- //- // See: [Note: Use looseObject when parsing JSON that will get persisted].- const {- id,- encryptedKey,- keyDecryptionNonce,- isDeleted,- metadata: encryptedMetadata,- magicMetadata: encryptedMagicMetadata,- pubMagicMetadata: encryptedPubMagicMetadata,- ...rest- } = remoteFile;-- // This flag is relevant only in the diff response, where it indicates that- // the file should be removed from the corresponding collection. We would've- // already acted on that information, so drop it from our local state.- ignore(isDeleted);-- const key = await decryptBox(- { encryptedData: encryptedKey, nonce: keyDecryptionNonce },- collectionKey,- );-- const metadataJSON = await decryptMetadataJSON(encryptedMetadata, key);- const metadata = FileMetadata.parse(- transformDecryptedMetadataJSON(id, metadataJSON),- );-- let magicMetadata: EnteFile["magicMetadata"];- if (encryptedMagicMetadata) {- const genericMM = await decryptMagicMetadata(- encryptedMagicMetadata,- key,- );- const data = FilePrivateMagicMetadataData.parse(genericMM.data);- magicMetadata = { ...genericMM, data };- }-- let pubMagicMetadata: EnteFile["pubMagicMetadata"];- if (encryptedPubMagicMetadata) {- const genericMM = await decryptMagicMetadata(- encryptedPubMagicMetadata,- key,- );- const data = FilePublicMagicMetadataData.parse(genericMM.data);- pubMagicMetadata = { ...genericMM, data };- }-- return { ...rest, id, key, metadata, magicMetadata, pubMagicMetadata };-};--/**- * Apply some transforms to gracefully handle metadata from old clients.- *- * @param metadataJSON The decrypted and parsed metadata JSON. Since TypeScript- * does not have a native JSON type, this is typed as an `unknown`.- *- * @returns A JSON object with any transformations applied, if needed.- */-export const transformDecryptedMetadataJSON = (- fileID: number,- metadataJSON: unknown,-) => {- // The file ID threshold is an arbitrary cutoff so that this graceful- // handling does not mask new issues.- if (fileID > 100000000) return metadataJSON;-- if (typeof metadataJSON != "object") return metadataJSON;- if (!metadataJSON) return metadataJSON;-- // In very rare cases (have found only one so far, a very old file in- // Vishnu's account, uploaded by an initial dev version of Ente) the photo- // has no modification time. Gracefully handle such cases.- if (- !("modificationTime" in metadataJSON) ||- !metadataJSON.modificationTime- ) {- if ("creationTime" in metadataJSON) {- log.info(`Patching metadata modification time for file ${fileID}`);- (metadataJSON as Record<string, unknown>).modificationTime =- metadataJSON.creationTime;- }- }-- // In very rare cases (again, some files shared with Vishnu's account,- // uploaded by dev builds) the photo might not have a file type. Gracefully- // handle these too.- if (- !("fileType" in metadataJSON) ||- typeof metadataJSON.fileType != "number"- ) {- log.info(`Patching metadata file type for file ${fileID}`);- (metadataJSON as Record<string, unknown>).fileType = FileType.image;- }-- return metadataJSON;-};--/**- * A short identifier for a file in log messages.- *- * e.g. "file flower.png (827233681)"- *- * @returns a string to use as an identifier when logging information about the- * given {@link file}. The returned string contains the file name (for ease of- * debugging) and the file ID (for exactness).- */-export const fileLogID = (file: EnteFile) =>- `file ${fileFileName(file)} (${file.id})`;diff --git a/web/apps/albums/vendor/ente-media/formats.ts b/web/apps/albums/vendor/ente-media/formats.tsdeleted file mode 100644index c2a98ca635..0000000000--- a/web/apps/albums/vendor/ente-media/formats.ts+++ /dev/null@@ -1,35 +0,0 @@-/**- * List used by {@link needsJPEGConversion}.- */-const needsJPEGConversionExtensions = [- "arw",- "cr2",- "cr3",- "dng",- "heic",- "jp2",- "nef",- "psd",- "rw2",- "tif",- "tiff",-];--/**- * Return `true` if {@link extension} is from amongst a known set of image file- * extensions that (a) we know that the browser is unlikely to support, and (b)- * which we should be able to convert to JPEG when running in our desktop app.- *- * These two are independent constraints, but we only return true if we satisfy- * both of them instead of having two disjoint lists.- */-export const needsJPEGConversion = (extension: string) =>- needsJPEGConversionExtensions.includes(extension.toLowerCase());--/**- * Return `true` if {@link extension} in for an HEIC-like file.- */-export const isHEICExtension = (extension: string) => {- const ext = extension.toLowerCase();- return ext == "heic" || ext == "heif";-};diff --git a/web/apps/albums/vendor/ente-media/heic-convert.ts b/web/apps/albums/vendor/ente-media/heic-convert.tsdeleted file mode 100644index 2eb561a6cb..0000000000--- a/web/apps/albums/vendor/ente-media/heic-convert.ts+++ /dev/null@@ -1,27 +0,0 @@-import { ComlinkWorker } from "ente-base/worker/comlink-worker";-import type { HEICConvertWorker } from "./heic-convert.worker";--/**- * Convert a HEIC image to a JPEG.- *- * Behind the scenes, it uses a web worker to do the conversion using a Wasm- * HEIC conversion package.- *- * @param heicBlob The HEIC blob to convert.- *- * @returns The JPEG blob.- */-export const heicToJPEG = async (heicBlob: Blob) =>- worker().then((w) => w.heicToJPEG(heicBlob));--/** Cached instance of the {@link ComlinkWorker} that wraps our web worker. */-let _comlinkWorker: ComlinkWorker<typeof HEICConvertWorker> | undefined;--/** Lazily created, cached, instance of our web worker. */-const worker = async () => (_comlinkWorker ??= createComlinkWorker()).remote;--const createComlinkWorker = () =>- new ComlinkWorker<typeof HEICConvertWorker>(- "heic-convert-worker",- new Worker(new URL("heic-convert.worker.ts", import.meta.url)),- );diff --git a/web/apps/albums/vendor/ente-media/heic-convert.worker.ts b/web/apps/albums/vendor/ente-media/heic-convert.worker.tsdeleted file mode 100644index 6ab4283fe7..0000000000--- a/web/apps/albums/vendor/ente-media/heic-convert.worker.ts+++ /dev/null@@ -1,37 +0,0 @@-import { expose } from "comlink";-import { logUnhandledErrorsAndRejectionsInWorker } from "ente-base/log-web";-import { wait } from "ente-utils/promise";-import HeicConvert from "heic-convert";--export class HEICConvertWorker {- /**- * Convert a HEIC file to a JPEG file.- *- * Both the input and output are blobs.- */- async heicToJPEG(heicBlob: Blob) {- const output = await heicToJPEG(heicBlob);- // I'm told this library used to have big memory spikes, and adding- // pauses to get GC to run helped. This might just be superstition tho.- await wait(10 /* ms */);- return output;- }-}--expose(HEICConvertWorker);--logUnhandledErrorsAndRejectionsInWorker();--const heicToJPEG = async (heicBlob: Blob): Promise<Blob> => {- const buffer = new Uint8Array(await heicBlob.arrayBuffer());- // [Note: Revisit some Node.js types errors post 22 upgrade]- //- // Going beyond "typescript" "5.6.3" we start seeing a type error here. This- // is possibly fixed in the newer Node.js types, but we're at 20 currently.- //- // eslint-disable-next-line @typescript-eslint/ban-ts-comment- // @ts-ignore- const result = await HeicConvert({ buffer, format: "JPEG" });- const convertedData = new Uint8Array(result);- return new Blob([convertedData], { type: "image/jpeg" });-};diff --git a/web/apps/albums/vendor/ente-media/image.ts b/web/apps/albums/vendor/ente-media/image.tsdeleted file mode 100644index 2912af02a4..0000000000--- a/web/apps/albums/vendor/ente-media/image.ts+++ /dev/null@@ -1,33 +0,0 @@-/**- * Compute optimal dimensions for a resized version of an image while- * maintaining aspect ratio of the source image.- *- * @param width The width of the source image.- *- * @param height The height of the source image.- *- * @param maxDimension The maximum width of height of the resized image.- *- * This function returns a new size limiting it to maximum width and height- * (both specified by {@link maxDimension}), while maintaining aspect ratio of- * the source {@link width} and {@link height}.- *- * It returns `{0, 0}` for invalid inputs.- */-export const scaledImageDimensions = (- width: number,- height: number,- maxDimension: number,-): { width: number; height: number } => {- if (width == 0 || height == 0) return { width: 0, height: 0 };- const widthScaleFactor = maxDimension / width;- const heightScaleFactor = maxDimension / height;- const scaleFactor = Math.min(widthScaleFactor, heightScaleFactor);- const resizedDimensions = {- width: Math.round(width * scaleFactor),- height: Math.round(height * scaleFactor),- };- if (resizedDimensions.width == 0 || resizedDimensions.height == 0)- return { width: 0, height: 0 };- return resizedDimensions;-};diff --git a/web/apps/albums/vendor/ente-media/live-photo.ts b/web/apps/albums/vendor/ente-media/live-photo.tsdeleted file mode 100644index 4830e23bd5..0000000000--- a/web/apps/albums/vendor/ente-media/live-photo.ts+++ /dev/null@@ -1,142 +0,0 @@-import {- fileNameFromComponents,- lowercaseExtension,- nameAndExtension,-} from "ente-base/file-name";-import JSZip from "jszip";-import { FileType } from "./file-type";--const potentialImageExtensions = [- "heic",- "heif",- "jpeg",- "jpg",- "png",- "gif",- "bmp",- "tiff",- "webp",-];--const potentialVideoExtensions = [- "mov",- "mp4",- "m4v",- "avi",- "wmv",- "flv",- "mkv",- "webm",- "3gp",- "3g2",- "avi",- "ogv",- "mpg",- "mp",-];--/**- * Use the file extension of the given {@link fileName} to deduce if is is- * potentially the image or the video part of a Live Photo.- */-export const potentialFileTypeFromExtension = (- fileName: string,-): FileType | undefined => {- const ext = lowercaseExtension(fileName);- if (!ext) return undefined;-- if (potentialImageExtensions.includes(ext)) return FileType.image;- else if (potentialVideoExtensions.includes(ext)) return FileType.video;- else return undefined;-};--/**- * An in-memory representation of a live photo.- */-interface LivePhoto {- imageFileName: string;- imageData: Uint8Array;- videoFileName: string;- videoData: Uint8Array;-}--/**- * Convert a binary serialized representation of a live photo to an in-memory- * {@link LivePhoto}.- *- * A live photo is a zip file containing two files - an image and a video. This- * functions reads that zip file (blob), and return separate bytes (and- * filenames) for the image and video parts.- *- * @param fileName The name of the overall live photo. Both the image and video- * parts of the decompressed live photo use this as their name, combined with- * their original extensions.- *- * @param zipBlob A blob contained the zipped data (i.e. the binary serialized- * live photo).- */-export const decodeLivePhoto = async (- fileName: string,- zipBlob: Blob,-): Promise<LivePhoto> => {- let imageFileName, videoFileName: string | undefined;- let imageData, videoData: Uint8Array | undefined;-- const [name] = nameAndExtension(fileName);- const zip = await JSZip.loadAsync(zipBlob, { createFolders: true });-- for (const zipFileName in zip.files) {- if (zipFileName.startsWith("image")) {- const [, imageExt] = nameAndExtension(zipFileName);- imageFileName = fileNameFromComponents([name, imageExt]);- imageData = await zip.files[zipFileName]?.async("uint8array");- } else if (zipFileName.startsWith("video")) {- const [, videoExt] = nameAndExtension(zipFileName);- videoFileName = fileNameFromComponents([name, videoExt]);- videoData = await zip.files[zipFileName]?.async("uint8array");- }- }-- if (!imageFileName || !imageData)- throw new Error(- `Decoded live photo ${fileName} does not have an image`,- );-- if (!videoFileName || !videoData)- throw new Error(`Decoded live photo ${fileName} does not have a video`);-- return { imageFileName, imageData, videoFileName, videoData };-};--/** Variant of {@link LivePhoto}, but one that allows files and data. */-interface EncodeLivePhotoInput {- imageFileName: string;- imageFileOrData: File | Uint8Array;- videoFileName: string;- videoFileOrData: File | Uint8Array;-}--/**- * Return a binary serialized representation of a live photo.- *- * This function takes the (in-memory) image and video data from the- * {@link livePhoto} object, writes them to a zip file (using the respective- * filenames), and returns the {@link Uint8Array} that represent the bytes of- * this zip file.- *- * @param livePhoto The in-mem photo to serialized.- */-export const encodeLivePhoto = async ({- imageFileName,- imageFileOrData,- videoFileName,- videoFileOrData,-}: EncodeLivePhotoInput) => {- const [, imageExt] = nameAndExtension(imageFileName);- const [, videoExt] = nameAndExtension(videoFileName);-- const zip = new JSZip();- zip.file(fileNameFromComponents(["image", imageExt]), imageFileOrData);- zip.file(fileNameFromComponents(["video", videoExt]), videoFileOrData);- return await zip.generateAsync({ type: "uint8array" });-};diff --git a/web/apps/albums/vendor/ente-media/magic-metadata.ts b/web/apps/albums/vendor/ente-media/magic-metadata.tsdeleted file mode 100644index 74bc85219d..0000000000--- a/web/apps/albums/vendor/ente-media/magic-metadata.ts+++ /dev/null@@ -1,228 +0,0 @@-import { decryptMetadataJSON, encryptMetadataJSON } from "ente-base/crypto";-import { nullishToZero } from "ente-utils/transform";-import { z } from "zod";--/**- * Zod schema of the mutable metadatum objects that we send to or receive from- * remote. It contains an encrypted metadata JSON object with some bookkeeping- * information attached.- *- * See {@link RemoteMagicMetadata} for the corresponding type.- */-export const RemoteMagicMetadata = z.object({- version: z.number(),- count: z.number().nullish().transform(nullishToZero),- data: z.string(),- header: z.string(),-});--/**- * The type of the mutable metadata fields, as represented by remote.- *- * See: [Note: Metadatum]- *- * This is the magic metadata that we send to and receive from remote. It- * contains an encrypted JSON object, and a version + count of entries to ensure- * that clients do not overwrite already applied updates with stale objects.- *- * When decrypt these into specific local {@link MagicMetadata} instantiations- * before using and storing them on the client.- */-export interface RemoteMagicMetadata {- /**- * Monotonically increasing iteration of this metadata object.- *- * The version starts at 1. Remote increments this version number each time- * a client updates the corresponding magic metadata field.- */- version: number;- /**- * The number of keys with non-nullish (i.e. not null and not undefined)- * values in the encrypted JSON object that the encrypted metadata blob- * contains.- *- * [Note: Magic metadata data cannot have nullish values]- *- * Clients are expected to retain the magic metadata verbatim so that they- * don't accidentally overwrite fields that they might not understand. See:- * [Note: Use looseObject for metadata Zod schemas]- *- * Remote enforces this by requiring that during edits and updates, this- * number should be greater than or equal to the previous version.- *- * Locally we enforce this in the {@link createMagicMetadata} function- * (which is used for both creation and updates), which trims off any- * entries in the data object whose value is `null` or `undefined` before- * arriving at the final object to use.- *- * This has the side effect that metadata entries cannot be deleted by- * setting their value to nullish. However usually the specific field- * semantics allow a reset to default behaviour by setting the value of the- * entry to the corresponding empty primitive (e.g. 0).- */- count: number;- /**- * The encrypted data.- *- * This are the base64 encoded bytes of the encrypted magic metadata JSON- * object.- *- * The encryption will happen using the "key" associated with the object- * whose magic metadata field this is. For example, if this is the- * {@link pubMagicMetadata} of an {@link EnteFile}, then the file's key will- * be used for encryption and decryption.- */- data: string;- /**- * The base64 encoded decryption header that will be needed for the client- * for decrypting {@link data}.- */- header: string;-}--/**- * The decrypted form of {@link RemoteMagicMetadata} used and locally persisted- * by the client.- *- * The bookkeeping fields ({@link version} and {@link count}) are copied over- * from the remote object ({@link RemoteMagicMetadata}), while the encrypted- * contents ({@link data} and {@link header} of {@link RemoteMagicMetadata}) are- * decrypted into a JSON object that is stored as {@link data}.- *- * Since different types of magic metadata fields are expected to contain- * different JSON objects as {@link data}, the type is generic, with the generic- * parameter `T` standing for the type of the JSON object.- *- * > Since TypeScript does not currently have a native JSON type, this T doesn't- * > have other constraints enforced by the type system, but it is meant to be a- * > JSON object.- *- * The word "magic metadata" by itself ambiguous. It refers to both the specific- * "magicMetadata" fields present in, say, the file and collection objects, and- * also to the shape of the structure this field shares with other semantically- * similar fields (e.g. public magic metadata). This type uses it in the second- * sense - to describe the shape of any of the magic metadata like fields used- * in various types. See: [Note: Metadatum].- */-export interface MagicMetadata<T = unknown> {- version: number;- count: number;- /**- * The "metadata" itself.- *- * This is expected to be a JSON object, whose exact schema depends on the- * magic metadata field in the parent object.- */- data: T;-}--/**- * Encrypt the provided magic metadata into a form that can be used in- * communication with remote, trimming the JSON object and updating the count.- *- * @param magicMetadata The decrypted {@link MagicMetadata} that is being used- * by the client.- *- * Any entries in {@link magicMetadata}'s {@link data} that are `null` or- * `undefined` are discarded before obtaining the final object that will be- * encrypted (and whose count will be used).- *- * So in particular, it is okay for the count in the {@link magicMetadata} to be- * out of sync with the count in the `data` JSON object because this function- * will recompute the count using the trimmed JSON object.- *- * @param key The base64 encoded key to use for encrypting the {@link data}- * contents of {@link magicMetadata}.- *- * The specific key used depends on the object whose magic metadata field this- * is meant for. For example, if this were the {@link pubMagicMetadata}- * associated with an {@link EnteFile}, then this would be the file's key.- *- * @returns a {@link RemoteMagicMetadata} object that contains the encrypted- * contents of the {@link data} present in the provided {@link magicMetadata}.- * The {@link version} is copied over from the provided {@link magicMetadata},- * while the {@link count} is obtained from the number of entries in the trimmed- * JSON object that was encrypted.- */-export const encryptMagicMetadata = async (- magicMetadata: MagicMetadata,- key: string,-): Promise<RemoteMagicMetadata> => {- const { version } = magicMetadata;-- const newMM = createMagicMetadata(magicMetadata.data);- const { count } = newMM;-- const { encryptedData: data, decryptionHeader: header } =- await encryptMetadataJSON(newMM.data, key);-- return { version, count, data, header };-};--/**- * A function to wrap an arbitrary JSON object in the {@link MagicMetadata}- * envelope used for the various magic metadata fields.- *- * A trimmed JSON object is obtained from the provided JSON object by removing- * any entries whose values is nullish (`null` or `undefined`).- *- * Then,- *- * - The `version` is set to provided value (or 1).- * - The `count` is set to the number of entries in the trimmed JSON object.- * - The `data` is set to the trimmed JSON object.- *- * {@link encryptMagicMetadata} internally uses this function to obtain an- * trimmed `data` and its corresponding `count`. This function is also exported- * for use in places where we just have a JSON object and would like to a new- * {@link MagicMetadata} object to house it from scratch.- *- * @param data A JSON object. Since TypeScript does not have a JSON type, this- * uses the `unknown` type.- *- * @param version An optional version number to use. This is useful when- * updating existing magic metadata, where the version in the update that we- * send to remote must match the existing version.- *- * If not provided, the 1 is used as the version.- */-export const createMagicMetadata = (data: unknown, version?: number) => {- // Discard any entries that with nullish (`null` or `undefined`) values.- //- // See: [Note: Magic metadata data cannot have nullish values]- const jsonObject = Object.fromEntries(- Object.entries(data ?? {}).filter(- ([, v]) => v !== null && v !== undefined,- ),- );-- const count = Object.keys(jsonObject).length;-- return { version: version ?? 1, count, data: jsonObject };-};--/**- * Decrypt the magic metadata received from remote into an object suitable for- * use and persistence by the client.- *- * This is meant as the inverse of {@link encryptMagicMetadata}, see that- * function's documentation for details.- */-export const decryptMagicMetadata = async (- remoteMagicMetadata: RemoteMagicMetadata,- key: string,-): Promise<MagicMetadata> => {- const {- version,- count,- data: encryptedData,- header: decryptionHeader,- } = remoteMagicMetadata;-- const data = await decryptMetadataJSON(- { encryptedData, decryptionHeader },- key,- );-- return { version, count, data };-};diff --git a/web/apps/albums/vendor/ente-utils/array.ts b/web/apps/albums/vendor/ente-utils/array.tsdeleted file mode 100644index dbdc214bb7..0000000000--- a/web/apps/albums/vendor/ente-utils/array.ts+++ /dev/null@@ -1,117 +0,0 @@-/**- * Shuffle.- *- * Return a new array containing the shuffled elements of the given array.- *- * The algorithm used is not the most efficient, but is effectively a one-liner- * whilst being reasonably efficient. To each element we assign a random key,- * then we sort by this key. Since the key is random, the sorted array will have- * the original elements in a random order.- */-export const shuffled = <T>(xs: T[]): T[] =>- xs- .map((x) => [Math.random(), x])- .sort()- .map(([, x]) => x) as T[];--/**- * Return a random sample of {@link n} elements from the given {@link items}.- *- * Functionally this is equivalent to `shuffled(items).slice(0, n)`, except it- * tries to be a bit faster for long arrays when we need only a small sample- * from it. In a few tests, this indeed makes a substantial difference.- *- * If {@link n} is less than the number of {@link items} then a random shuffle- * of the {@link items} is returned.- */-export const randomSample = <T>(items: T[], n: number) => {- if (items.length <= n) return shuffled(items);- if (n == 0) return [];-- if (n > items.length / 3) {- // Avoid using the random sampling without replacement method if a- // significant proportion of the original items are needed, otherwise we- // might run into long retry loop at the tail end (hitting the same- // indexes again an again).- return shuffled(items).slice(0, n);- }-- const ix = new Set<number>();- while (ix.size < n) {- ix.add(Math.floor(Math.random() * items.length));- }- return [...ix].map((i) => items[i]!);-};--/**- * Return the first non-empty string from the given list of strings.- *- * This function is needed because the `a ?? b` idiom doesn't do what you'd- * expect when a is "". Perhaps the behaviour is wrong, perhaps the expectation- * is wrong; this function papers over the differences.- *- * If none of the strings are non-empty, or if there are no strings in the given- * array, return undefined.- */-export const firstNonEmpty = (- ss: (string | undefined)[],-): string | undefined => {- for (const s of ss) if (s && s.length > 0) return s;- return undefined;-};--/**- * Merge the given array of {@link Uint8Array}s in order into a single- * {@link Uint8Array}.- *- * @param as An array of {@link Uint8Array}.- */-export const mergeUint8Arrays = (as: Uint8Array[]): Uint8Array => {- // A longer but better performing replacement of- //- // new Uint8Array(as.reduce((acc, x) => acc.concat(...x), []))- //-- const len = as.reduce((len, xs) => len + xs.length, 0);- const result = new Uint8Array(len);- as.reduce((n, xs) => (result.set(xs, n), n + xs.length), 0);- return result;-};--/**- * Break an array into batches of size {@link chunkSize}.- *- * @returns An array of the resultant batches.- */-export const batch = <T>(xs: T[], batchSize: number): T[][] => {- const batches: T[][] = [];- for (let i = 0; i < xs.length; i += batchSize) {- batches.push(xs.slice(i, i + batchSize));- }- return batches;-};--/**- * Split an array into two arrays - those that satisfy the given- * {@link predicate}, and those that don't.- *- * @param xs The array to split.- *- * @param predicate A function invoked for each element, to decide which part of- * the split it will belong to.- *- * @returns A tuple with two arrays. The first of these arrays contains all- * elements for which the predicate returned `true`, and the second array- * contains the rest of the elements.- */-export const splitByPredicate = <T>(- xs: T[],- predicate: (t: T) => boolean,-): [T[], T[]] =>- xs.reduce<[T[], T[]]>(- (result, x) => {- (predicate(x) ? result[0] : result[1]).push(x);- return result;- },- [[], []],- );diff --git a/web/apps/albums/vendor/ente-utils/ensure.ts b/web/apps/albums/vendor/ente-utils/ensure.tsdeleted file mode 100644index 9be5215bf5..0000000000--- a/web/apps/albums/vendor/ente-utils/ensure.ts+++ /dev/null@@ -1,60 +0,0 @@-/**- * Throw an exception if the given value {@link v} is false-y.- *- * This is a variant of {@link assertionFailed}, except it always throws, not- * just in dev builds, if the given value is falsey.- */-export const ensurePrecondition = (v: unknown): void => {- if (!v) throw new Error("Precondition failed");-};--/**- * Throw an exception if the given value is `null` or `undefined`.- *- * This is different from TypeScript's built in null assertion operator `!` in- * that `ensure` involves a runtime check, and will throw if the given value is- * null-ish. On the other hand the TypeScript null assertion is only an- * indication to the type system and does not involve any runtime checks.- *- * However, still it is preferable to use the TypeScript build in null assertion- * since the stack traces are more informative. The stack trace is not at the- * point of the assertion, but later at the point of the use, so it is not- * _directly_ pointing at the issue, but usually it is not hard to backtrace.- *- * Still, in rare cases we might want to, well, ensure that a undefined value- * doesn't sneak into the machinery. So this.- */-export const ensure = <T>(v: T | null | undefined): T => {- if (v === null) throw new Error("Required value was null");- if (v === undefined) throw new Error("Required value was undefined");- return v;-};--/**- * Throw an exception if the given value is not a string.- */-export const ensureString = (v: unknown): string => {- if (typeof v != "string")- throw new Error(`Expected a string, instead found ${String(v)}`);- return v;-};--/**- * Throw an exception if the given value is not a number or if it is NaN.- */-export const ensureNumber = (v: unknown): number => {- if (typeof v != "number" || Number.isNaN(v))- throw new Error(`Expected a number, instead found ${String(v)}`);- return v;-};--/**- * Throw an exception if the given value is not an integral number.- */-export const ensureInteger = (v: unknown): number => {- if (typeof v != "number")- throw new Error(`Expected a number, instead found ${String(v)}`);- if (!Number.isInteger(v))- throw new Error(`Expected an integer, instead found ${v}`);- return v;-};diff --git a/web/apps/albums/vendor/ente-utils/promise.ts b/web/apps/albums/vendor/ente-utils/promise.tsdeleted file mode 100644index 19a0311a7e..0000000000--- a/web/apps/albums/vendor/ente-utils/promise.ts+++ /dev/null@@ -1,157 +0,0 @@-/**- * Wait for {@link ms} milliseconds- *- * This function is a promisified `setTimeout`. It returns a promise that- * resolves after {@link ms} milliseconds.- */-export const wait = (ms: number): Promise<void> =>- new Promise((resolve) => setTimeout(resolve, ms));--/**- * Throttle invocations of an underlying function, coalescing pending calls.- *- * Take a function that returns a promise, and return a new function that can be- * called an any number of times while still ensuring that the underlying- * function is only called a maximum of once per the specified period.- *- * The underlying function is immediately called if there were no calls to the- * throttled function in the last period.- *- * Otherwise we start waiting. Multiple calls to the throttled function while- * we're waiting (either for the original promise to resolve, or after that, for- * the specified cooldown period to elapse) will all be coalesced into a single- * call to the underlying function when we're done waiting.- *- * ---- *- * [Note: Throttle and debounce]- *- * There are many throttle/debounce libraries, and ideally I'd have liked to- * just use one of them instead of reinventing such a basic and finicky wheel.- * Then why write a bespoke one?- *- * - "debounce" means that the underlying function will only be called when a- * particular wait time has elapsed since the last call to the _debounced_- * function.- *- * - This behaviour, while useful sometimes, is not what we want always. If the- * debounced function is continuously being called, then the underlying- * function might never get called (since the wait time does not elapse).- *- * - To avoid this starvation, some debounce implementations like lodash provide- * a "maxWait" option, which tells the debounced function to always call the- * underlying function if maxWait has elapsed.- *- * - The debounced functions can trigger the underlying in two ways: leading- * (aka immediate) and trailing which control if the underlying should be- * called at the leading or the trailing edge of the time period.- *- * - "throttle" can be conceptually thought of as just maxWait + leading. In- * fact, this is how lodash actually implements it too. So we could've used- * lodash, except that is a big dependency to pull for a small function.- *- * - Alternatively, pThrottle is a micro-library that provide such a "throttle"- * primitive. However, its implementation enqueues all incoming requests to- * the throttled function: it still calls the underlying once per period, but- * eventually underlying will get called once for each call to the throttled- * function.- *- * - There are circumstances where that would be the appropriate behaviour, but- * that's not what we want. We wish to trigger an async action, coalescing- * multiple triggers into a single one, one per period.- *- * - Perhaps there are other focused and standard library that'd have what we- * want, but instead of spending more time searching I just wrote it from- * scratch for now. Indeed, I've spent more time writing about the function- * than the function itself.- */-export const throttled = (- underlying: () => Promise<void>,- period: number,-): (() => void) => {- let pending = 0;-- const f = () => {- pending += 1;- if (pending > 1) return;- void underlying()- .then(() => wait(period))- .then(() => {- const retrigger = pending > 1;- pending = 0;- if (retrigger) f();- });- };-- return f;-};--/**- * Await the given {@link promise} for {@link timeoutMS} milliseconds. If it- * does not resolve within {@link timeoutMS}, then reject with a timeout error.- *- * Note that this does not abort {@link promise} itself - it will still get- * settled, just its eventual state will be ignored if it gets fulfilled or- * rejected after we've already timed out.- */-export const withTimeout = async <T>(- promise: Promise<T>,- ms: number,-): Promise<T> => {- let timeoutId: ReturnType<typeof setTimeout>;- const rejectOnTimeout = new Promise<T>((_, reject) => {- timeoutId = setTimeout(- () => reject(new Error("Operation timed out")),- ms,- );- });- const promiseAndCancelTimeout = async () => {- const result = await promise;- clearTimeout(timeoutId);- return result;- };- return Promise.race([promiseAndCancelTimeout(), rejectOnTimeout]);-};--/**- * A promise queue to serialize execution of bunch of promises.- *- * Promises can be added to the queue with the {@link add} function, which- * returns a new promise that'll settle when the original promise settles.- *- * The queue will ensure that promises run sequentially one after the other, in- * the order which they are added.- */-export class PromiseQueue<T> {- private q: { task: () => Promise<T>; handlers: unknown }[] = [];-- /**- * Add a promise to the queue, and return a new promise that will resolve to- * the provided promise when it gets a chance to run (after all previous- * promises in the queue have settled).- *- * @param task To avoid starting the promise resolution when adding them,- * instead of the promise itself, {@link add} takes a function that should- * return the promise that we wish to await.- */- async add(task: () => Promise<T>): Promise<T> {- let handlers;- const p = new Promise<T>((...args) => (handlers = args));- this.q.push({ task, handlers });- if (this.q.length == 1) this.next();- return p;- }-- private next() {- const item = this.q[0];- if (!item) return;- const { task, handlers } = item;- void task()- // @ts-expect-error Can't think of an easy way to satisfy tsc.- .then(...handlers)- .finally(() => {- this.q.shift();- this.next();- });- }-}diff --git a/web/apps/albums/vendor/ente-utils/transform.ts b/web/apps/albums/vendor/ente-utils/transform.tsdeleted file mode 100644index 6934f78b25..0000000000--- a/web/apps/albums/vendor/ente-utils/transform.ts+++ /dev/null@@ -1,26 +0,0 @@-/**- * Convert `null` to `undefined`, passthrough everything else unchanged.- */-export const nullToUndefined = <T>(v: T | null | undefined): T | undefined =>- v === null ? undefined : v;--/**- * Convert `null` and `undefined` to `false`, passthrough everything else unchanged.- */-export const nullishToFalse = (v: boolean | null | undefined): boolean =>- v ?? false;--/**- * Convert `null` and `undefined` to `0`, passthrough everything else unchanged.- */-export const nullishToZero = (v: number | null | undefined): number => v ?? 0;--/**- * Convert `null` and `undefined` to "" (blank string), passthrough everything else unchanged.- */-export const nullishToBlank = (v: string | null | undefined): string => v ?? "";--/**- * Convert `null` and `undefined` to `[]`, passthrough everything else unchanged.- */-export const nullishToEmpty = <T>(v: T[] | null | undefined): T[] => v ?? [];diff --git a/web/apps/albums/vendor/ente-utils/type-guards.ts b/web/apps/albums/vendor/ente-utils/type-guards.tsdeleted file mode 100644index 1309a5bea4..0000000000--- a/web/apps/albums/vendor/ente-utils/type-guards.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * A variant of Array.includes that allows us to use it as a type guard.- *- * It allows us to narrow the type of an arbitrary T to U if it is one of U[].- *- * TypeScript currently doesn't allow us to use the standard Array.includes as a- * type guard for checking if an arbitrary string is one of the known set of- * values. This issue and this workaround is mentioned here:- * - https://github.com/microsoft/TypeScript/issues/48247- * - https://github.com/microsoft/TypeScript/issues/26255#issuecomment-502899689- */-export function includes<T, U extends T>(us: readonly U[], t: T): t is U {- // @ts-expect-error @typescript-eslint/no-unsafe-argument- return us.includes(t);-}