Initial commit
Some checks failed
/ Build App (push) Failing after 48s

This commit is contained in:
Valentin Brandl 2024-07-17 00:26:05 +02:00
commit e9e599b78f
Signed by: vbrandl
GPG Key ID: CAD4DA1A789125F9
28 changed files with 5314 additions and 0 deletions

8
.containerignore Normal file
View File

@ -0,0 +1,8 @@
node_modules
.git
.prettierignore
.prettierrc
Containerfile
README.md

1
.envrc Normal file
View File

@ -0,0 +1 @@
use flake

30
.gitea/workflows/node.yml Normal file
View File

@ -0,0 +1,30 @@
on:
workflow_call:
push:
branches:
- main
pull_request:
schedule:
- cron: "0 0 * * *"
jobs:
node:
name: Build App
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: https://gitea.com/actions/checkout@v4
- name: Setup Node
uses: https://gitea.com/actions/setup-node@v4
with:
node-version: 20
- name: Install dependencies
run: npm ci
- name: Lint
run: npm lint
- name: Check
run: npm check
- name: Test
run: npm test
- name: Build
run: npm run build

24
.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
node_modules
# Output
.output
.vercel
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
uploads
.direnv

1
.npmrc Normal file
View File

@ -0,0 +1 @@
engine-strict=true

4
.prettierignore Normal file
View File

@ -0,0 +1,4 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock

8
.prettierrc Normal file
View File

@ -0,0 +1,8 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
}

15
Containerfile Normal file
View File

@ -0,0 +1,15 @@
FROM node:21 AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:21
USER node:node
WORKDIR /app
COPY package.json .
COPY --from=builder /app/build ./build
CMD ["node", "./build/index.js"]

38
README.md Normal file
View File

@ -0,0 +1,38 @@
# create-svelte
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/main/packages/create-svelte).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm create svelte@latest
# create a new project in my-app
npm create svelte@latest my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.

33
eslint.config.js Normal file
View File

@ -0,0 +1,33 @@
import js from '@eslint/js';
import ts from 'typescript-eslint';
import svelte from 'eslint-plugin-svelte';
import prettier from 'eslint-config-prettier';
import globals from 'globals';
/** @type {import('eslint').Linter.FlatConfig[]} */
export default [
js.configs.recommended,
...ts.configs.recommended,
...svelte.configs['flat/recommended'],
prettier,
...svelte.configs['flat/prettier'],
{
languageOptions: {
globals: {
...globals.browser,
...globals.node
}
}
},
{
files: ['**/*.svelte'],
languageOptions: {
parserOptions: {
parser: ts.parser
}
}
},
{
ignores: ['build/', '.svelte-kit/', 'dist/']
}
];

61
flake.lock Normal file
View File

@ -0,0 +1,61 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1710146030,
"narHash": "sha256-SZ5L6eA7HJ/nmkzGG7/ISclqe6oZdOZTNoesiInkXPQ=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "b1d9ab70662946ef0850d488da1c9019f3a9752a",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1720957393,
"narHash": "sha256-oedh2RwpjEa+TNxhg5Je9Ch6d3W1NKi7DbRO1ziHemA=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "693bc46d169f5af9c992095736e82c3488bf7dbb",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

22
flake.nix Normal file
View File

@ -0,0 +1,22 @@
{
description = "A very basic flake";
inputs = {
nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
};
outputs = { self, nixpkgs, flake-utils }:
flake-utils.lib.eachDefaultSystem
(system:
let
pkgs = (import nixpkgs) {
inherit system;
};
in {
devShell = pkgs.mkShell {
nativeBuildInputs = with pkgs; [ nodejs ];
};
}
);
}

4712
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

39
package.json Normal file
View File

@ -0,0 +1,39 @@
{
"name": "fotochallenge",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"test": "vitest",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --check . && eslint .",
"format": "prettier --write ."
},
"devDependencies": {
"@sveltejs/adapter-auto": "^3.0.0",
"@sveltejs/adapter-node": "^5.2.0",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
"@types/eslint": "^8.56.7",
"@types/node": "^20.14.11",
"eslint": "^9.0.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.36.0",
"globals": "^15.0.0",
"prettier": "^3.1.1",
"prettier-plugin-svelte": "^3.1.2",
"svelte": "^4.2.7",
"svelte-check": "^3.6.0",
"tslib": "^2.4.1",
"typescript": "^5.0.0",
"typescript-eslint": "^8.0.0-alpha.20",
"vite": "^5.0.3",
"vitest": "^1.2.0",
"bulma": "^1.0.1",
"sass": "^1.77.5"
},
"type": "module"
}

11
src/app.d.ts vendored Normal file
View File

@ -0,0 +1,11 @@
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}

12
src/app.html Normal file
View File

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

15
src/app.scss Normal file
View File

@ -0,0 +1,15 @@
/* Override global Sass variables from the /utilities folder */
@use 'bulma/sass/utilities' with (
$link: $pink
);
@use 'bulma/sass/base' with (
$body-overflow-y: auto
);
/* Import the components you need */
@use 'bulma/sass/elements';
@use 'bulma/sass/form';
@use 'bulma/sass/components';
@use 'bulma/sass/grid';
@use 'bulma/sass/helpers';
@use 'bulma/sass/layout';
@use 'bulma/sass/themes';

8
src/index.test.ts Normal file
View File

@ -0,0 +1,8 @@
import safePath from '$lib';
import { describe, it, expect } from 'vitest';
describe('safe path', () => {
it('removes non alphanum from string', () => {
expect(safePath('../../!=-.,/abc123')).toBe('abc123');
});
});

5
src/lib/index.ts Normal file
View File

@ -0,0 +1,5 @@
// place files you want to import through the `$lib` alias in this folder.
const safePath = (input: string) => input.replace(/\W/g, '');
export default safePath;

9
src/routes/+error.svelte Normal file
View File

@ -0,0 +1,9 @@
<script>
import { page } from '$app/stores';
</script>
{#if $page.status === 404}
<div class="box">
<h3>Seite nicht gefunden. <a href="/">Zurück zur Startseite.</a></h3>
</div>
{/if}

47
src/routes/+layout.svelte Normal file
View File

@ -0,0 +1,47 @@
<script>
import '../app.scss';
</script>
<header>
<section class="section">
<div class="container is-max-desktop">
<div class="columns">
<div class="column is-two-thirds is-offset-one-fifth">
<h1 class="title">Gabi und Hannes Fotochallenge</h1>
<h2 class="subtitle">Lösungen für die Fotochallenge</h2>
</div>
</div>
</div>
</section>
</header>
<main id="wrapper">
<section class="section">
<div class="container is-max-desktop">
<div id="content">
<div class="columns">
<div class="column is-half is-offset-one-quarter">
<slot />
</div>
</div>
</div>
</div>
</section>
</main>
<style>
:global(body) {
display: flex;
min-height: 100vh;
flex-direction: column;
}
#wrapper {
flex: 1;
}
#content {
text-align: justify;
hyphens: auto;
}
</style>

View File

@ -0,0 +1,60 @@
import { writeFileSync, mkdirSync, existsSync } from 'fs';
import { fail } from '@sveltejs/kit';
import type { RequestEvent } from './$types';
import safePath from '$lib';
import { hash } from 'crypto';
import path from 'path';
const storagePath: string = './uploads';
const mkdirIfNotExists = (path: string) => {
if (!existsSync(path)) {
mkdirSync(path);
}
};
export const actions = {
default: async ({ request }: RequestEvent) => {
const data = await request.formData();
const formFiles = data.getAll('files');
if (!formFiles) {
return fail(400, { field: 'files', files: formFiles, missing: true });
} else if (!(formFiles as File[])) {
return fail(400, { field: 'files', files: formFiles, incorrect: true });
}
const files = formFiles as File[];
console.log(files);
if (files.length === 0) {
return fail(400, { field: 'files', files: formFiles, empty: true });
}
const formName = data.get('name');
if (!formName) {
return fail(400, { field: 'name', name: formName, missing: true });
} else if (!(formName as string)) {
return fail(400, { field: 'name', name: formName, incorrect: true });
}
const name = safePath(formName as string);
files.forEach(async (file) => {
const outPath = `${storagePath}/${name}`;
const content = Buffer.from(await file.arrayBuffer());
const ext = path.extname(file.name);
mkdirIfNotExists(outPath);
const filename = hash('sha1', content);
const fullPath = `${outPath}/${filename}${ext}`;
if (existsSync(fullPath)) {
console.warn(`${fullPath} has already been uploaded. Skipping...`);
} else {
writeFileSync(fullPath, Buffer.from(await file.arrayBuffer()), { flag: 'a+' });
}
});
return {
success: true
};
}
};

94
src/routes/+page.svelte Normal file
View File

@ -0,0 +1,94 @@
<script lang="ts">
import { enhance } from '$app/forms';
import type { ActionData } from './$types';
export let form: ActionData;
let files: FileList;
let sending = false;
const siPrefixes = new Map([
[1_000_000, 'M'],
[1_000, 'k']
]);
const fileSize = (files: FileList) => {
const size = Array.from(files)
.map((f) => f.size)
.reduce((a, b) => a + b, 0);
return (
Array.from(siPrefixes)
.filter(([k]) => size >= k)
.map(([k, v]) => `${(size / k).toFixed(1)} ${v}B`)[0] ?? `${size} bytes`
);
};
</script>
<form
enctype="multipart/form-data"
class="box"
method="POST"
use:enhance={() => {
sending = true;
return ({ update }) => {
update({ invalidateAll: true }).finally(async () => {
sending = false;
});
};
}}
>
{#if sending}
<div class="notification is-info">Wird hochgeladen...</div>
{:else if form?.success}
<div class="notification is-success">Erfolgreich hochgeladen</div>
{/if}
<div class="field">
<label for="name" class="label">Name</label>
<div class="control">
<input
id="name"
class="input"
type="text"
name="name"
placeholder="Name"
value={form?.name ?? ''}
required
/>
</div>
{#if form?.field === 'name'}
{#if form?.missing}
<p class="help is-danger">Bitte einen Namen angeben</p>
{:else if form?.incorrect}
<p class="help is-danger">Ungültiger Name</p>
{/if}
{/if}
</div>
<div class="file is-centered has-name is-boxed">
<label class="file-label">
<input class="file-input" type="file" name="files" bind:files multiple required />
<span class="file-cta">
<span class="file-label">Fotos auswählen...</span>
</span>
{#if files}
<span class="file-name"
>{files.length} Bild{#if files.length > 1}er{/if} ausgewählt ({fileSize(files)})</span
>
{:else}
<span class="file-name">Keine Bilder ausgewählt</span>
{/if}
{#if form?.field === 'files'}
{#if form?.missing || form?.empty}
<p class="help is-danger">Bitte mindestens eine Datei auswählen</p>
{:else if form?.incorrect}
<p class="help is-danger">Ungültige Dateien</p>
{/if}
{/if}
</label>
</div>
<div class="field is-grouped is-grouped-centered">
<div class="control">
<button class="button is-link">Hochladen</button>
</div>
</div>
</form>

2
src/variables.scss Normal file
View File

@ -0,0 +1,2 @@
/* Set your brand colors */
$pink: pink;

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

18
svelte.config.js Normal file
View File

@ -0,0 +1,18 @@
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
// for more information about preprocessors
preprocess: vitePreprocess(),
kit: {
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://kit.svelte.dev/docs/adapters for more information about adapters.
adapter: adapter()
}
};
export default config;

19
tsconfig.json Normal file
View File

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
// except $lib which is handled by https://kit.svelte.dev/docs/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

18
vite.config.ts Normal file
View File

@ -0,0 +1,18 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vitest/config';
export default defineConfig({
plugins: [sveltekit()],
test: {
include: ['src/**/*.{test,spec}.{js,ts}']
},
css: {
preprocessorOptions: {
scss: {
additionalData: '@use "src/variables.scss" as *;'
}
}
}
});