Closed4

2024年4月の学習記録

miroscularmiroscular

4月の目標

AOJ

6問
213ページ ALDS1_8_A Binary Search Tree Iまで

--> 1_7_C まで

個人開発

DynamoDBにキャッシュを100件追加
DynamoDB, spotify search API とのなめらかな連携
簡潔なUIの完成
プレイリスト作成機能までつなぎこみ

--> DynamoDBにキャッシュは追加したものの、データ構造の変更を余儀なくされる
TiDBへの以降を検討中
簡潔なUIは作成済み、プレイリスト作成機能はまだ

Terraform / AWS

https://pages.awscloud.com/JAPAN-event-OE-Hands-on-for-Beginners-StaticWebsiteHosting-2022-reg-event.html?trk=aws_introduction_page
AWS 上で静的な Web サイトを公開しよう!

https://pages.awscloud.com/JAPAN-event-OE-Hands-on-for-Beginners-CF_WAF-2022-reg-event.html?trk=aws_introduction_page
Amazon CloudFrontおよびAWS WAFを用いて エッジサービスの活用方法を学ぼう

上記2つをTerraformで構築

さらに、今のうちにクレジットを使ってドメインを取得する

teraform のポリシーを使ってcostのコントロール
https://developer.hashicorp.com/terraform/tutorials/cloud-get-started/cost-estimation

--> AWS 上で静的な Web サイトを公開しよう!
に関してはTerraformで構築済み
ドメイン取得も完了
ポリシーでのコストコントロールは未完、他に優先すべき事柄があるため当分保留
lambdaでpackageごとnodeをデプロイする方法を検討中
web adapterの試用、AWS SAMの利用
AWS SAM を使ってテンプレートからサーバーレスな環境を構築する ハンズオン完了

Frontend Mentor

https://tailwindpractice.netlify.app/
掲載されている残り2つのプロジェクトを完遂させる

--> Learning Path に従って学習することに
代わりに以下の2つのプロジェクトを完遂
https://www.frontendmentor.io/challenges/blog-preview-card-ckPaj01IcS/hub
https://www.frontendmentor.io/challenges/base-apparel-coming-soon-page-5d46b47f8db8a7063f9331a0/hub

Next.js

Next.js の以下公式ドキュメント読了

https://nextjs.org/docs/app/building-your-application/data-fetching
data fetching * 3
https://nextjs.org/docs/app/building-your-application/rendering
rendering * 4
https://nextjs.org/docs/app/building-your-application/testing
testing * 2
https://nextjs.org/docs/app/building-your-application/authentication
authentication
https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config
route-segment-config
https://github.com/vercel/next.js/blob/canary/examples/next-forms/app/page.tsx
form の実装例
https://nextjs.org/blog/security-nextjs-server-components-actions
next.js security

--> authenticationまで読了

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks
CSSの構成要素 のコンテンツ読了
→一旦 テキストの方向 までとして、CSSレイアウトの50%読了を目指す

--> そろそろ飽きてきた&文章が読みづらいので挫折
レイアウト編をピックアップして読了&個人のQiita記事で代用
https://qiita.com/kura07/items/486c19045aab8090d6d9#自動的に配置

記録

4/30

AOJ

ALDS1_7_D
木の復元

個人開発

https://docs.pingcap.com/tidb/stable/quick-start-with-tidb
tidbでローカルサーバーを作る
Grafana, prometheus も自動で作られ、モダンなダッシュボードもある

https://docs.pingcap.com/tidb/stable/dev-guide-transaction-overview
Transactionの概要を読めとのこと
optimistic transaction, pessimistic transaction の2種類
transaction isolation levels について
アプリケーション側の責任でのリトライ、エラーハンドリングなど
optimistic transactionが何なのか知らない場合は、伝統的なpessimisticを使うべき

sqlのcommit とは何なのか
トランザクション独立レベルとは何なのか

次回
https://docs.pingcap.com/tidb/stable/dev-guide-build-cluster-in-cloud
https://docs.pingcap.com/tidb/stable/dev-guide-sample-application-nextjs

Terraform / AWS

元々、iam roleの作成にはassume roleの指定が必要
Trust policy として作成している
何のサービスに対するroleを作るか?というところでpolicyが変わる
それからpermissionsで AmazonDynamoDBFullAccess を与えたりなど

https://www.ctc-g.co.jp/solutions/cloud/column/article/76.html
permissions boundary とは何なのか?

https://tech.dentsusoken.com/entry/essence_of_iam_permissions_boudary
iam permissions boundary
特定のユーザーがロール作成するのを許可しつつ、権限昇格を防止する
iam管理者委任などで便利らしい

既存のコードだと、index.tsの変更を検知してくれない
色々と問題がありすぎるので、これやめたほうが良さそう

lambda web adapterの例を参考にしたほうが良くないか?

次回
以下ページの方法を参考にもう一度ゼロからトライする
https://so-wh.at/entry/2024/02/04/114048

Frontend Mentor

https://www.frontendmentor.io/challenges/recipe-page-KiTsR8QQKm/hub
レスポンシブ対応完成
次回こだわりポイントを明文化、他人のコードとの比較

Next.js

Data Transfer Object
canSeeUserName のような関数を用意して現在のユーザーが取得可能かどうかを判定させる

Layoutでデータフェッチする必要がある場合は、Layoutで認証をするのではなく、
データソースに出来る限り近い場所で認証を行う。フェッチする関数の中で認証する

server actionはpublic APIのごとくきちんと認証すること

次回 next security
https://nextjs.org/blog/security-nextjs-server-components-actions

MDN CSS

grid 解説記事
https://qiita.com/kura07/items/e633b35e33e43240d363#ステップ3---方法a-ラインの番号で指定する

各アイテムでtrackの番号を振って配置する方法、
container部分でアスキーアートのように指定する方法の二つがある

https://qiita.com/kura07/items/486c19045aab8090d6d9
grid-auto-rows で事前に指定した分の長さをはみ出したコンテンツの縦の長さを決められる

次回 自動的に配置 から

4/29

type-challenge/leetcode

https://leetcode.com/problems/top-travellers/description/
サブクエリ不要

https://github.com/type-challenges/type-challenges/blob/main/questions/00003-medium-omit/README.ja.md
union に対して in を使うことでdistributeにオブジェクトが定義できたりする

In TypeScript 4.1 and later versions, the as keyword can also be used in mapped types for remapping key names. This allows you to change the names of keys when creating new types.
新しいマップ型を作成する際にasを使うことでキーの名前を変更できる

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-1.html#key-remapping-in-mapped-types
要するに、asで変更できるのはmapped typeのkeyにあたる部分の模様

https://zenn.dev/uhyo/articles/typescript-intrinsic
なぞのintrinsic keyword

個人開発

https://www.cockroachlabs.com/blog/react-typescript-cockroachdb-sample-app/#deploy-the-application-to-netlify
cockroach db + react example

https://docs.pingcap.com/tidb/stable
情報量の多さ、日本での採用事例の多さを考慮するとTiDBで構築するほうが良さそう

https://pingcap.co.jp/pricing/
料金もcockroachDBと変わらない

AWSとの相性も良さげ

DMMでの採用事例もある

次回
以下読む
https://docs.pingcap.com/tidb/stable/dev-guide-overview

必要なところを理解したら以下でチュートリアル
https://docs.pingcap.com/tidb/stable/dev-guide-sample-application-nextjs

Terraform / AWS

https://github.com/rahman95/terraform-lambda-typescript-starter
ビルド、デプロイ作業を全てTerraformでやるのではなく、
あくまでTerraformは既存のファイルをクラウドとどう通信するのか、を決定する
統合的なコマンドはyarnに任せるパターン

assume role とは何か?
https://zenn.dev/fusic/articles/1538897dd8f092
iam roleのポリシーに記述するアクション。
やはりassume roleがよくわからない。EC2のときはどう記述すればよい?

iam roleに記述する場合と、assume roleに同じlambdaのアクセスを許可する場合でなにが違う?

次回
Terraform で構築したリソースをいじってTerraformがどのように実際のリソースに影響するか調べる

4/27

type-challenge/leetcode

https://leetcode.com/problems/capital-gainloss/description/
sum(if())構文で簡単

https://github.com/type-challenges/type-challenges/blob/main/questions/03057-easy-push/README.ja.md
Push

https://github.com/type-challenges/type-challenges/blob/main/questions/03060-easy-unshift/README.ja.md
unshift

https://github.com/type-challenges/type-challenges/blob/main/questions/03312-easy-parameters/README.ja.md
parameter

type MyParameters<T extends (...args: any[]) => any> = T extends (...args: infer params) => any
  ? [params]
  : never
// 関数のパラメータを上記の形式でinferすると、例えば以下の例では[[arg1: string]]が取得できる

function hoge(arg1: string): void { }
type a = MyParameters<typeof hoge>

https://github.com/type-challenges/type-challenges/blob/main/questions/00002-medium-return-type/README.ja.md
get return type

Function型というのもある

個人開発

次回
https://www.cockroachlabs.com/docs/v23.2/deploy-app-vercel?#step-1-get-the-code
cockroach db と vercel でNext.js アプリを作るチュートリアル

Terraform / AWS

zipでlambdaをアップロードする方法

  • aws_lambda_function でlambdaを作成
    s3にコードをアップロードする方法
    s3_key ってなんだっけ?
    オブジェクトから取得したkey を指定すればよさげ

  • aws_s3_bucket で空のbucketを作成

  • null_resource でローカルでビルドを行う
    npm install, build
    aws s3 cp

s3_bucket_server_side_encryption_configuration とは?
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_server_side_encryption_configuration
サーバーサイドの暗号化設定について

こんな面倒なスクリプトをくまなくても出来る方法はありそうなもの。

次回

かなり丁寧な解説付き。
https://leejjon.medium.com/use-terraform-to-create-an-aws-lambda-function-that-runs-your-typescript-code-b805db667a93

シンプルなスクリプトで解決している
https://github.com/rahman95/terraform-lambda-typescript-starter

4/26

AOJ

https://onlinejudge.u-aizu.ac.jp/status/users/DJ_wata/submissions/1/ALDS1_7_C/judge/9138837/C++14

type-challenge/leetcode

  • Typescriptの Equal util type について詳細
    https://zenn.dev/yumemi_inc/articles/ff981be751d26c
    要するに、Conditional type そのもの同士の比較を行った際に
    コンパイラ内部で型の正確な比較が行われる、ということ

Terraform / AWS

https://dev.classmethod.jp/articles/deploy-typescript-lambda-function-with-terraform/
こちらを参考に構築

null resource とは?
指定したコマンドを実行するためのリソース
何もプロビジョニングしない
triggers を設定することでどんなときに発火するか決める

fileset パターンに一致する複数のfile名の配列を返す
https://developer.hashicorp.com/terraform/language/functions/fileset

次回 全行にコメント解説を書く もしくは口頭説明

Frontend Mentor

https://tailwindcss.com/docs/justify-content
flexと一緒に使うのは justify-content

https://tailwindcss.com/docs/justify-items
gridと使うのはjustify-items

Next.js

https://nextjs.org/docs/app/building-your-application/authentication#creating-a-data-access-layer-dal
サーバーで動作するverifySession関数を定義
セッションを複合してユーザーidを取得
dbにアクセスしてユーザーidからユーザー情報を取得する

middlewareとの役割の違いは?
sessionが正しく保存されているかどうか

DALは具体的にユーザー情報をDBから引き出すような用途

次回 server componentsから
https://nextjs.org/docs/app/building-your-application/authentication#server-components

MDN CSS

https://qiita.com/kura07/items/e633b35e33e43240d363

#container {
    display: grid;
    grid-template-rows: 100px 50px;
    grid-template-columns: 150px 1fr;
}

まずこれらのプロパティで 行の高さ、列の幅を決める
150px と 1fr が共存しているとき、 frは残り全部 という意味になる
もちろんfrの単位の考え方は活かされる

ラインの番号でアイテムの配置を決定する方法と、アスキーアートのようにエリアに名前をつけて指定する方法がある
後者をtailwindcssで使うにはどうすればよい?

次回
https://jsfiddle.net/kura07/3edx9ad2/2/
このサンプルをいじって、ゼロから2通りの方法でレイアウトを実現する
Tailwindcssではgridをどのように扱っているのか
https://qiita.com/kura07/items/486c19045aab8090d6d9
場面別編

4/25

type-challenge/leetcode

配列に対してkeyofを呼んだら?

type c1<T> = {[P in keyof T]: P}
type cc1 = c1<[{hoge: string, fuga: number}, 2, 3, 4, true, string]>

"1", "2" とかが返ってくる
配列も広義でオブジェクト?

https://github.com/type-challenges/type-challenges/issues/1568#issuecomment-1571089203

type Includes<T extends readonly any[], U> = IsEqual<{
  [P in keyof T as T[P] extends U ? 0 : never]: T[P]
}, { 0: U }>

genericsの中で使う型Tのことを 型パラメーター type parameter とよぶ

genericsでは、asであり得なさそうな型変換も出来る

type a1<T> = {
  [P in keyof T as never]: T[P]
}
type ac1 = a1<[1, 2]>

T as string
のような型変換は不可能

下記はエラーになる

type f1<T> = { [P in keyof (T as (0 | 1))]: string }

keyofが結びついているのはあくまでその直後の型まで
下記で、b1とd1は等価
つまり、asによって型推論されるのはstringの部分ではなく (keyof string) の部分

type b1 = { [P in keyof string as 0 | 1]: string }
// --> { 0: string, 1: string}
type c1 = { [P in keyof (0 | 1)]: string }
// --> { toString: string; ... }
type d1 = { [P in (0 | 1)]: string }
// --> { 0: string, 1: string}
type g1 = { [P in (keyof string) as (0 | 1)]: string }
// --> { 0: string, 1: string}

型定義の中でasが使えるのは、keyofによるもの、かつ配列のキー指定の場所 だけの模様

個人開発

https://www.cockroachlabs.com/docs/v23.2/start-a-local-cluster-in-docker-linux
cockroach db をlinux localで使う方法

https://www.npmjs.com/package/string-similarity
string similarity などを使って単語の類似度を測る

Terraform / AWS

node_moduleが必要な関数をlambdaで実行するにはどうすればよいのか?

次回これを一通り手を動かしてみる
https://dev.classmethod.jp/articles/deploy-typescript-lambda-function-with-terraform/

Next.js

authorizationの方法

optimistic
cookieを使う方法
UIを表示するか否か、ロールによってユーザーをリダイレクトするか否か

secure
databaseに格納されているセッションデータを使う方法
センシティブなデータへのアクセスが必要となるケース

セッションを格納した後、どうやってサーバー側でチェックする?
optimistic checkであれば、middlewareでcookieを受け取って行う
全てのrouteで使われるので、部外者を弾きやすい
ただ、これがデータを守るための唯一のディフェンスラインになってはならない。

次回 data access layerから
https://nextjs.org/docs/app/building-your-application/authentication#creating-a-data-access-layer-dal

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/CSS_layout/Grids#グリッドフレームワーク
公式の説明だと正直なにがなんだか全然わからないので別のサイトを参考にする

次回は以下を読んで理解を深める
https://qiita.com/kura07/items/e633b35e33e43240d363

4/24

AOJ

https://teramonagi.hatenablog.com/entry/20120623/1340429460
参照返しの関数で参照で受け取りを行うとコピーコンストラクタが使われなくて済む

個人開発

https://chat.openai.com/share/ab7272c5-b8fa-4c4a-852e-54046c8f3219

LibROSA: Pythonで曲の特徴抽出や類似性比較を行うためのライブラリです。音楽解析や機械学習にも利用されます。
Echo Nest Remix: Echo NestのAPIを利用したPythonライブラリで、曲のビートやキー、テンポなどの解析が可能です。
Essentia: C++で曲の特徴抽出を行うライブラリで、PythonやMATLABなどの言語からも利用可能です。
AcousticID: 音響指紋を利用して曲の一致を判定するライブラリで、MusicBrainzと連携しています。

Deezer API: Deezerは音楽ストリーミングサービスで、APIを介して曲のメタデータや音響指紋を取得できます。Node.js向けのDeezer APIクライアントがあり、これを使用して曲の一致を判定できます。
MusicBrainz API: MusicBrainzはオープンな音楽データベースで、APIを介して曲のメタデータを取得できます。Node.js向けのMusicBrainz APIクライアントがあり、これを使用して曲の一致を判定できます。
AcousticID API: AcousticIDは音響指紋を利用して曲の一致を判定するサービスで、APIを介して利用できます。Node.js向けのAcousticID APIクライアントがあります。

色々なネットサービスがある
MusicBrainz も曲名に関する情報が載っていいてAPIもあるので分析に使えそう

Terraform / AWS

https://docs.aws.amazon.com/ja_jp/eventbridge/latest/userguide/eb-run-lambda-schedule.html
チュートリアルにしたがって、lambda関数を作成してからevent schedule を作成する
余計なiam role, policyが作成されるので、まとめて削除しておく

次回
lambda関数の作成とevent scheduleの作成をまた1から
Terraformで同じものを構築し直す
TaskChuteの更新関数をnodeで実装する

4/22

type-challenge/leetcode

世にも奇妙なboolean型
boolean = true | false 説?

https://qiita.com/charon1212/items/f06db517e3e8e3550c99
検証している記事があった

type Includes<T extends readonly any[], U> = T extends [infer V, ...infer W]
  ? V extends U
    ? true
    : Includes<W, U>
  : string

type foo = Includes<[boolean], false>

実際、foo型は true | string になる

  ? V extends U

の時点で、 (true | false) extends false
になっているとすると、2回それぞれに対してextendsが判定され、一方は再帰しfalseを返し、
一方はtrueとして変えるためunion typeになる

type Includes<T extends readonly any[], U> = T extends [infer V, ...infer W]
  ? [V] extends [U]
    ? true
    : Includes<W, U>
  : false

タプル化すると望み通りの挙動になる

distributive な挙動を見せるのはgenericsのときだけ

type bar<T> = T extends 1 ? true : false
type b = bar<1 | 2> // --> boolean
type hoge = (1 | 2) extends 1 ? true : false // --> false

個人開発

https://qiita.com/walkers/items/49ad7dbee36dbef7d8dc
DynamoDBではソートキー以外での絞り込みができない
whereが便利に使えない

https://qiita.com/maaz118/items/9e198ea91ad8fc624491
hasura
勝手にGraphQLサーバーを作ってくれるスグレモノ

Terraform / AWS

https://aws.amazon.com/jp/builders-flash/202009/awsgeek-eventbridge/?awsf.filter-name=*all
イベントバスとは?
何かAWS上のサービスで同じバス内のイベントが発生した際、条件を満たすかチェックされる
イベントグループみたいなもの?

event archiveを作成すると、managedなevent ruleが作成される

https://qiita.com/ishibashi-futoshi/items/586ebe17b174a478eb6a
Event Bridgeとは?

AWS policy
principal 許可を与える対象、もの
resource ポリシーで取り扱う対象、たとえばS3のオブジェクトとか

誰に対して(principal)、なに(resource)に対する操作(action)を許可(Effect: allow)するか?
どんなときに?(Condition)

次回 lambda関数のスケジュール
https://docs.aws.amazon.com/ja_jp/eventbridge/latest/userguide/eb-run-lambda-schedule.html

Next.js

https://nextjs.org/docs/app/building-your-application/authentication#stateless-sessions
stateless session の作り方

  1. シークレットキーを作る(署名、復号に使う)
  2. sessionを暗号化、復号するロジックを作る encrypt 関数の引数としては、userId, expiresAt などを渡す
  3. cookies() を使ってクッキーの管理を行う

https://nextjs.org/docs/app/building-your-application/authentication#database-sessions
次回 database sessions

MDN CSS

.container {
  display: grid;
  /* grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); */
  grid-template-columns: repeat(2, 1fr); // 1fr は画面分割単位 2列を配置するということ
  grid-auto-rows: minmax(100px, auto); // カードの高さは最小で100px, コンテンツが肥大したら自動で拡大する
  gap: 20px;
}
.container {
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}

横方向 最低200px, 最大で1単位
auto-fit でこれらの基準を満たしながら、配置される数が変化する
200px ~ 1fr とはどういう意味なのか?

次回
収まる限り多くの列 から

4/21

type-challenge/leetcode

https://leetcode.com/problems/replace-employee-id-with-the-unique-identifier/solutions/3549131/sql-left-join-easy-solution/
left join するだけの簡単な問題

https://github.com/type-challenges/type-challenges/issues/1568
なぜEqualが動作するのか?

type Includes<T extends readonly any[], U> = T extends [infer V, ...infer W]
  ? V extends U
    ? true
    : Includes<W, U>
  : false
type foo = Includes<[boolean], false>

なぜこれがワークしないのか?
なぜ、foo typeはbooleanになってしまうのか?
TypeChallengeのdiscordがあったのでここで質問してみる

さらに沢山の独自 utility type を集めたもの
https://github.com/piotrwitek/utility-types?tab=readme-ov-file

Terraform / AWS

sam init で対話的にsamプロジェクトを初期化出来る
sam buildでtemplateを作成
sam deploy --guided
で対話的にデプロイ出来る。スタックの名前とかも決められる
sam local start-lambda
sam local start-api
などでデプロイする前にローカルで検証可能

https://docs.aws.amazon.com/ja_jp/eventbridge/latest/userguide/eb-get-started.html
eventbridge を使えば、タスクをスケジュールして実行することが可能

次回
https://docs.aws.amazon.com/ja_jp/eventbridge/latest/userguide/eb-tutorial-archive-replay.html
チュートリアルを簡単にこなす

eventbridge + lambda でtaskchuteの雑務タスク自動追加

Frontend Mentor

listに振られる連番の色の変更は
marker:text-orange-900 などで行う
marker:font-bold など

そこまで細かい調整はできない

Next.js

useFormStatus を使う場合は、 formタグの中で使う。

  • capture user credentials
    formでパスワード、メールなどをFormState型で受け取り、サーバーアクションに渡す

  • validate form fields on the server
    サーバー側で、Zodなどを使ってバリデーションを行う

  • create a user or check user credentials
    問題があればエラーを表示

セッション管理ライブラリ
library such as iron-session or Jose.

次回 Stateless Sessions
https://nextjs.org/docs/app/building-your-application/authentication#stateless-sessions

MDN CSS

flex: 1 auto
について

https://tailwindcss.com/docs/flex
最初のサイズを保持しつつも、画面幅をできるだけ満たそうとする

次回 グリッドから
https://developer.mozilla.org/ja/docs/Learn/CSS/CSS_layout/Grids

その他

4/20

type-challenge/leetcode

https://github.com/type-challenges/type-challenges/blob/main/questions/00268-easy-if/README.ja.md
2種類の extends を上手く使えれば簡単

https://github.com/type-challenges/type-challenges/blob/main/questions/00533-easy-concat/README.ja.md
infer を使った冗長な回答

type Concat<T extends readonly any[], U extends readonly any[]> = T extends readonly [...infer V]
  ? U extends readonly [...infer W]
    ? [...V, ...W]
    : never
  : never

これでよい

type Concat<T extends readonly any[], U extends readonly any[]> = [...T, ...U]

https://typescriptbook.jp/reference/statements/unknown
unknown型とは? anyとの違いは?
型安全なany型
型を絞り込まなければ、unknown型を別の変数に代入することができないし、メソッド呼び出しもできない

https://typescriptbook.jp/reference/functions/type-guard-functions
型ガード関数
ifによって型を絞り込むことで、Typescriptが安全だと判断してエラーを出さずに関数を実行できたりする
typeof instanceofを使って型ガードが出来るが、それ以外にも独自に型ガード関数を定義することができる

zod, superstructなどのライブラリを使うと、沢山のプロパティのチェックを簡単に行える

https://github.com/type-challenges/type-challenges/blob/main/questions/00898-easy-includes/README.ja.md

個人開発

引き続きUIの整備
spotifyのUIを見倣う

Terraform / AWS

DynamoDBテーブル作成, lambda連携
AmazonDynamoDBFullAccess のポリシー名が DynamoDBFullAccess となっていたためずっとエラー
次回 sam CLIのハンズオンから

Frontend Mentor

w-96がMAX?
max-w-lg とかを使うとより大きな画面幅を実現できる
max-width とwidth ってなにが違うのか?どういうときに使い分ける

Next.js

https://nextjs.org/_next/image?url=%2Fdocs%2Fdark%2Fauthentication-overview.png&w=1920&q=75
教育上、ベーシックなパスワード、ユーザーネーム認証で進める
基本はauthentication libraryを使うことが推奨されている

https://nextjs.org/docs/app/building-your-application/authentication
認証の流れ
全然わからない

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/CSS_layout/Flexbox#flex_一括指定対個別指定
一括指定対個別指定から

orderを指定して、若い方から先に表示させることも出来る

https://css-tricks.com/snippets/css/a-guide-to-flexbox/
flexboxについてわかりやすい例

次回 ネストしたフレックスボックス から
https://github.com/mdn/learning-area/blob/main/css/css-layout/flexbox/complex-flexbox.html

https://zenn.dev/t_kitamura/articles/cbecc45853a959
grid と flexの違いについてわかりやすい

その他

AppImage をubuntuランチャーから起動する方法
https://askubuntu.com/questions/1328196/how-can-i-create-a-desktop-entry-for-an-appimage
要するに、/usr/share/application か ~/.local/share/application のどちらかに *.desktop を作成すればよい

miroscularmiroscular

4/18

AOJ / type-challenge

https://qiita.com/k-penguin-sato/items/e2791d7a57e96f6144e5
Utility typeについて

https://onlinejudge.u-aizu.ac.jp/status/users/DJ_wata/submissions/1/ALDS1_7_B/judge/9111824/C++14
再帰で高さを求める

個人開発

https://github.com/tailwindlabs/prettier-plugin-tailwindcss?tab=readme-ov-file
tailwindcss prettier の利用

https://prettier.io/docs/en/configuration.html
.prettierrc.ymlで、以下のように書く

plugins:
  - prettier-plugin-tailwindcss

個人開発で色々気をつける点まとめ
SEOについても
https://sabigara.com/posts/indie-hacking-stack

Terraform / AWS

https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format
lambda の出力フォーマットについて

https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/sam-property-function-eventsource.html
Events以降で指定するできるパラメータについて

Frontend Mentor

https://zenn.dev/onikun/articles/28fb8de056c89a
hydration failed エラーについて
tableの中に直接文字とかを入れていると駄目っぽい

Next.js

https://nextjs.org/docs/app/building-your-application/testing/vitest
こちらを参考にvitestを導入

https://testing-library.com/docs/react-testing-library/example-intro
まずReact Testing Library の理解が必要になりそう

https://vitest.dev/guide/
その上でVitestを利用する利点は?まとめて実行など?

Next.js の公式実例
https://github.com/vercel/next.js/blob/canary/examples/with-vitest/tests/Home.test.tsx

次回 testは一旦先送りにするとして、authenticationの実装について
https://nextjs.org/docs/app/building-your-application/authentication
authentication

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/CSS_layout/Normal_Flow
垂直方向にマージンが重なると、総裁が起きて大きい方のマージンのみが適用される

https://developer.mozilla.org/ja/docs/Learn/CSS/CSS_layout/Flexbox
あまり使わなそうだが、 flex-direction: row-reverse とかを指定したり出来る

flex: number
を指定することで、要素ごとにどれだけの主軸に対して幅を使うかの割合を表示できる

mdnでは以下で見られる
https://developer.mozilla.org/ja/docs/Web/CSS/flex

Tailwindでの対応は以下
https://tailwindcss.com/docs/flex

次回
flex: 一括指定対個別指定

4/17

type-challenge/leetcode

https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types

extends any とは何なのか?
https://stackoverflow.com/questions/69333281/whats-the-difference-between-t-extend-any-and-t

conditional typesで展開するために便宜的に使っている模様

https://qiita.com/suin/items/b9d00dff380486338ecd
promiseLike とは何なのか?
then メソッドを持っているオブジェクトのこと

個人開発

突然ですが、ここで Typescriptの型システムについて、中上級者向けのクイズを出題します。

graphql-codegen などで、APIのクエリから型定義を自動生成できたりする。
例えばこんな感じで、ListQuery型が自動生成される。

type ListQuery = {
  __typename?: "Query";
  MediaListCollection?: {
    __typename?: "MediaListCollection";
    lists?: Array<{
      __typename?: "MediaListGroup";
      entries?: Array<{
        __typename?: "MediaList";
        media?: {
          __typename?: "Media";
          id: number;
          title?: {
            __typename?: "MediaTitle";
            native?: string | null;
            romaji?: string | null;
            english?: string | null;
          } | null;
          coverImage?: {
            __typename?: "MediaCoverImage";
            extraLarge?: string | null;
            large?: string | null;
          } | null;
        } | null;
      } | null> | null;
    } | null> | null;
  } | null;
};
type MediaArray = {
  __typename?: "Media";
  id: number;
  title?: {
    __typename?: "MediaTitle";
    native?: string | null;
    romaji?: string | null;
    english?: string | null;
  } | null;
  coverImage?: {
    __typename?: "MediaCoverImage";
    extraLarge?: string | null;
    large?: string | null;
  } | null;
}[];

開発をしていると、こんな感じで部分的に型を抜き出したくなるようなことがある。
もちろん、こうやって型を抜き出してコピペして自前で定義して使ってもよい。
しかし、他人が作ったAPIから自動生成した型ListQueryは、APIの仕様変更で
attributeが増えたり減ったり、あるいはネスト構造が変化するかも知れない。
その度に自前で定義した型を再定義しないといけないのは、非常に面倒。

どうにかして、ListQueryのみをsingle source of truth として
MediaArray型をエレガントに生成することはできないだろうか?

但し、APIの仕様が変わったりしたとしても
__typename?: "Media"というattributeは
必ず持つという仕様は変更されないとする。

私はこの問題について真に驚くべき解法を発見したが、ここに記すには余白が狭すぎる。

Terraform / AWS

https://qiita.com/Shoma0210/items/17193f254180396fb8e1
リソースベースのポリシーはS3にjsonではっつけたりするやつ
アイデンティティベースのは、IAMやロールにつけるやつ

https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-policies
policies に追加することで色々簡単に付与できる
iamのポリシー画面に入力されているのと同じ文字列を入れればOK

次回 API gateway, dynamoDB連携 & SAM CLIダウンロード

Frontend Mentor

https://tailwindcss.com/docs/gap
flex と gap を組み合わせることで、ボックス内で要素を並べる時に空白を指定できる

https://tailwindcss.com/docs/container
画面の表示幅に応じてwidthが変わる要素
これとmx-autoを使ってformatする方法がある

mx-autoは一つのコンテンツにしか適用できないので、複数のカードがあったりしたら全部揃えるのに
全部にmx-autoを指定しないといけない
個人的には justify-center, items-center を使うべきと考える

Next.js

https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
edge runtime
middlewareのために使われるランタイム
使えるAPIが限られている

https://nextjs.org/docs/app/building-your-application/rendering#network-boundary
next.js では、サーバー側もクライアント側も同じコードを使うのでコンテクストスイッチのコストがかからない。
どのコードがサーバーで実行されるべきで、クライアントで実行されるのかをしっかり理解することが重要

次回 Testing
https://nextjs.org/docs/app/building-your-application/testing/vitest

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/CSS_layout/Introduction#位置指定のテクニック

position:

  • relative
    本来その要素があるべき位置から、ずらす
  • absolute
    ページの一番上から、ずらした位置に配置する
    要素はその場所になかったものとして扱われる
  • fixed
    画面上に固定されたように見える
  • sticky
    特定の場所までスクロールすると、fixedと同じような動作になる
    表の一番上のカラムだけ残したいときとか、便利そう

次回通常フローから
https://developer.mozilla.org/ja/docs/Learn/CSS/CSS_layout/Normal_Flow

4/16

AOJ

https://stackoverflow.com/questions/5134614/why-cant-i-access-elements-with-operator-in-a-const-stdmap
const map では、operator[] は使えないので代わりにatを使う

https://docs.oracle.com/cd/E19957-01/805-7887/6j7dsdheo/index.html
関数テンプレートを使って、任意のtypeのinputを行う関数を作りconstでcinできるようにする

個人開発

vscodeの特定のsnipetを無効にしたい
class スニペット
classNameを入力しようとしていつも間違える
特定のsnipetのオーバーライドは難しい模様

flex flex-row, flex-col を駆使して一定の表形式で要素を並べられるように

Terraform / AWS

AWS SAM handson

sourceファイルにはローカルパスを指定して良い
aws cloudformation package
することでzip化されたコードが指定されたs3にアップロードされて、適切なpathに変換される

以下の記述をyamlに足すことで、cloudformationがsamの拡張記法を使えるようになる

Transform: AWS::Serverless-2016-10-31
Resources:
  TranslateLambda: # 関数名
    Type: AWS::Serverless::Function # lambdaのこと。

Type: AWS::Serverless::Function 以外にも、下記に指定した様々なリソースが使える

https://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/sam-specification-resources-and-properties.html

# package
aws cloudformation package \
     --template-file template.yaml \
     --s3-bucket *your-backet-name* \
     --output-template-file packaged-template.yaml

# deploy
aws cloudformation deploy \
     --template-file ./packaged-template.yaml \
     --stack-name hands-on-serverless-2 \
     --capabilities CAPABILITY_IAM

https://zenn.dev/mjxo/articles/34abb31874e662
なぜ --capabilities CAPABILITY_IAM が必要なのか
→結局よくわからない。IAMリソースを作成する場合があるとき、とあるが作るのはlambdaではないのか

Failed to create/update the stack. Run the following command
to fetch the list of events leading up to the failure
aws cloudformation describe-stack-events --stack-name hands-on-serverless-2

なんか作成が上手く行かない
cloudformation のマネージメントコンソールに行く
python3.7がサポートされていないことに起因するエラーの模様
一旦stackを削除して、packageしなおして、s3にアップロードし直して再度トライする

完了
iam policyとかがどうなっているのかと思ったら、自動で作成されている
lambdaのconfiguration, view role documentから確認可能

Frontend Mentor

カスタムプロパティを利用
bg-[color:hsl(0,90%,90%)]

frontend mentor 提出
https://www.frontendmentor.io/solutions/with-nextjs-react-typescript-tailwindcss-sTcCQcJ3N1

Next.js

https://nextjs.org/docs/app/building-your-application/caching#react-cache-function
https://ja.react.dev/reference/react/cache
React cache function

App router で使ってみる

cache は、サーバコンポーネントでのみ使用できます。
RSCのことも指しているので、おそらく'use client'以外では使える

cacheの引数に指定するものがプリミティブでないもの、例えばオブジェクトなどは
毎回作成するような形だと別のものの参照だと考えられてキャッシュがヒットしない
https://github.com/sniper-fly/Otaku-GPaT/commit/ac0803fb0e6a0b837aaadcb565121faf6cdb5df5
上記はcacheのテストを行ったもの

次回
https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes
edge runtimesについて

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/CSS_layout/Introduction

ブロックの方向 横書きモードでは、下方向
インライン方向 `` 右方向

grid と flex の違い
flex は一次元的な制御、gridは二次元的な制御

昔はfloat を使ってflex grid の代用をして段組みレイアウトを組んでいたらしい
floatの使いみちがわからない

次回 位置指定のテクニック から

4/14

AOJ

ALDS1_7_B
再帰関数を使って木の深さ、高さを調べる
高さ => 葉までの再長距離

再帰関数が書けるようになってきている

個人開発

https://zenn.dev/kterui9019/articles/c340f2ae4d8c58
dynamodbのクエリ結果を安全に扱う方法について

ReturnTypeというユーティリティタイプがあり、関数をgenericsに指定すると戻り値が取得できる

type BatchGetParams = ReturnType<typeof convertToBatchGetParams>;

https://zenn.dev/miya_tech/articles/0dde1228045af6
凝集度とは?復習

https://zenn.dev/taiga533/articles/e08ad4f4af5577079b5b
結合度の話

Terraform / AWS

https://medium.com/@ryan.cormack/comparing-container-and-zip-lambdaliths-with-thin-functions-03b439239e72
zip と docker でlambda web adapter を比較してみたベンチマーク記事

https://github.com/awslabs/aws-lambda-web-adapter

Non-AWS base images may be used since the Runtime Interface Client ships with the Lambda Web Adapter.

COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:0.8.2 /lambda-adapter /opt/extensions/lambda-adapter

どんなイメージでも、常軌を追加するだけで使える模様

https://blog.inductor.me/entry/alpine-not-recommended
distrolessイメージの勧め
alpineは安定性の観点から使わないほうが良いとのこと

https://zenn.dev/the_exile/articles/75269a81f49f62
lambda web adapter と distroless を使っている例
golangじゃないと難しそう?

マルチステージビルドで、nodeのパッケージが更新された場合とかは再度イメージビルドしないと駄目?

https://zenn.dev/jrsyo/articles/e42de409e62f5d
node.js のモダンなdocker構成について

Frontend Mentor

box-shadow の作り方について
https://developer.mozilla.org/ja/docs/Web/CSS/box-shadow

box-shadow: x-offset, y-offset, 色
を指定する
3つのsize関係の引数があった場合、ぼかし半径を決められる

tailwindではarbitrary value で以下のように
shadow-[10px_10px_black]

transition クラスでhover時などの動作をtransitionに出来る
transition-shadow
transition-color
など、対象を限定することも可能

https://www.frontendmentor.io/learning-paths
learning path にしたがって進むのも良さそう

次回 READMEの改訂とpublish

Next.js

https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns
fetchはデフォルトでcacheされる
fetch以外を使うときは、cacheを使うべし

https://nextjs.org/docs/app/building-your-application/caching#react-cache-function
これはサーバーサイドでも使えるのか?

npm i server-only
でインストールすることで、'server-only' が記載できるように成り、
これがclient側でimportされたりするとbuild time error が発生する

→あとで実際に試す
同様にclient-onlyもあるらしい

実験してみた。
import 'server-only'
が記載されているファイル上のサーバーアクションを、'use client' 宣言されている
componentで使うと以下のようなエラー

One of these is marked as a client entry with "use client":
  ./app/dashboard/customers/serverOnlyFn.ts
  ./app/dashboard/customers/page.tsx
 ⨯ ./app/dashboard/customers/serverOnlyFn.ts
ReactServerComponentsError:

You're importing a component that needs server-only. That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.
Learn more: https://nextjs.org/docs/getting-started/react-essentials

https://qiita.com/honey32/items/bc24d8c0ea3d096ff956
https://qiita.com/honey32/items/4d04e454550fb1ed922c
非常に参考になる記事2つ、正直公式読むよりこっち読んだほうが良かったすらある
モダンな設計パターンについてと、NextApp routerでそれを実現する方法について

次回
https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#using-third-party-packages-and-providers

Reactのcache関数を試す

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Handling_different_text_directions
今までの物理プロパティには、対応する論理プロパティが存在する
margin-top は margin-block-start にマップされ、
padding-left は padding-inline-start にマップされる
これによってテキストの方向によらず一貫して描画が出来る

次回から 要素のはみ出し を飛ばして CSS layoutに入る
https://developer.mozilla.org/ja/docs/Learn/CSS/CSS_layout

4/13

type-challenge/leetcode

list of product
https://leetcode.com/problems/list-the-products-ordered-in-a-period/submissions/1085037887/

type-challenge
https://github.com/type-challenges/type-challenges/blob/main/questions/00043-easy-exclude/README.ja.md

https://github.com/type-challenges/type-challenges/issues/54#issuecomment-1788619163
conditional type は、union型に対しては分配的に、個別に評価される
distributive conditional types と呼ばれる
https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types

そのため、以下の意味が一見不明なtypeでは、

type MyExclude<T, U> = T extends U ? never : T

union型の|で区切られたそれぞれについて評価される

そろそろinferを理解する
https://qiita.com/ehika/items/8f41d4a3c8f9df4af9c3

conditional type としての
extends の右辺につけることができる

T extends (infer U) => string ? U : never

引数の型を取り出せる

type First<T extends any[]> = T extends [infer A, ...infer rest] ? A : never

このように残りの不定数の引数を表すようなことも可能

型条件分岐の中でまさか再帰を行うことになるとは...
https://github.com/type-challenges/type-challenges/blob/main/questions/00189-easy-awaited/README.ja.md

個人開発

failed to satisfy constraint: Member must have length less than or equal to 100
BatchGetCommand では、最大で100件のクエリまでしか検索できない
2重配列を作って、100件ずつクエリする

Terraform / AWS

https://github.com/vercel/next.js/blob/canary/examples/with-docker/Dockerfile
docker で next.jsのマルチステージビルドを行う場合のプラクティス

https://github.com/awslabs/aws-lambda-web-adapter/tree/main/examples/nextjs
nextjs を web adapter で起動する例

lambda関数は最大で15分実行可能

Frontend Mentor

blog-preview-card-main
この程度の簡単なレイアウトなら何も見なくてもある程度作れるようになった
わからないところだけ参考サイトのを見て学習すれば良さげ

Next.js

However, "use client" doesn't need to be defined in every component that needs to be rendered on the client. Once you define the boundary, all child components and modules imported into it are considered part of the client bundle.
use client を使っているファイル内でimportするコンポーネントは全てclient componentになるってことか?
client component の中でSuspenseを使っても意味がない?

Next.js はreact APIを使って、static HTMLを生成する機能を使っているので、最初のページロードは
server component, client component ともにクライアントがparseしたりダウンロードしなくていい

次回 composition pattern
https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns
client, server componentの連結パターン色々

MDN CSS

vertical-rl: 右から左へのブロックの流れの方向。文は垂直に実行されます。
vertical-lr: 左から右へのブロックの流れの方向。文は垂直に実行されます。

違いがわからない
rl 縦書きで、右から左に文章が配置される

書き込みモードが縦になると、ブロックの方向は横になり、インラインの方向は縦になる
height, width の設定方向は変わらないので(物理)、論理的なバージョンに置き換えることで両対応できる

次回以下から
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Handling_different_text_directions#論理マージン、ボーダー、パディングのプロパティ

その他

https://qiita.com/fsd_maclala/items/8f8bcd168e70ce0ab59c
could not read source map for file
デバッグ時エラーの解決方法
それでも1個のエラーだけは残って気持ちが悪い
remoteRoot, localRoot を設定している場合は設定不要ぽい

4/12

AOJ

ALDS1_7_B
二分木の高さ

個人開発

テスタビリティのため、BatchGetCommand のためのparameter整形は別関数で実施
リクエストのやりとりは別の関数の責務とする

Terraform / AWS

bucketポリシーの削除、public access blockの設定でs3への直接のアクセスは禁じられるが、
これだとCloudfrontからもアクセスできない模様

X-Cache: Error from cloudfront
が返ってくる
そもそもoriginってなんだっけ?
S3など、コンテンツ提供元のこと

https://dev.classmethod.jp/articles/amazon-cloudfront-origin-access-control/
OACの設定方法について
origin access controle を作って、s3のbucket policyを変更する必要がある
どんなpolicyをコピースべきかはコンソールで教えてくれる

https://docs.aws.amazon.com/ja_jp/IAM/latest/UserGuide/reference_policies_elements_condition.html
iam policyのcondition要素について
特定の条件の時にのみポリシーが適用されるように出来る
condition-key で、AWS:SourceArn 、 aws:username などを指定する
それぞれのサービスには固有のコンテキストキーがあるので、それを利用する
terraform では、variableがこれに相当する

https://zenn.dev/kou_pg_0131/articles/tf-cloudfront-oac
oac の設定値について参考

AWSからs3に設定するように渡されたjson

{
    "Version": "2008-10-17",
    "Id": "PolicyForCloudFrontPrivateContent",
    "Statement": [
        {
            "Sid": "AllowCloudFrontServicePrincipal",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudfront.amazonaws.com"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::anitunes.click/*",
            "Condition": {
                "StringEquals": {
                  "AWS:SourceArn": "arn:aws:cloudfront::xxxx:distribution/xxxx"
                }
            }
        }
    ]
  }

https://dev.classmethod.jp/articles/amazon-cloudfront-origin-access-control/
oacの以前はoaiが使われていた
AWSハンズオンではOAIの解説だった

S3ハンズオン、Terraformで完全再現は達成
次回 lambda web adapter

Frontend Mentor

https://github.com/vercel/next.js/issues/53715
Imageがなぜか表示されない

<Image 
  src={`${basePath}/image-avatar.webp`}
  width={64}
  height={64}
  alt="image-avatar"
  className="m-3"
/>

svgは表示できるし、imgタグで同じsrcを指定しても動く
400 Bad Request
Unable to optimize image and unable to fallback to upstream image

  const basePath = "/blog-preview-card-main";
  const basePath = "/blog-preview-card-main/";

スラッシュがあるなしだけの違いだった
svgは/が多くても処理できるが、他の画像形式はスラッシュが多いと処理できないらしい
多くのOSではディレクトリに/が重なっていたとしても一つとして処理するがNext.jsはその機能を持ってない模様

Next.js

https://nextjs.org/docs/app/building-your-application/rendering/server-components#static-rendering-default
server component

Next.jsでは、static rendering と dynamic rendering を混在させることが出来る
ページをすべて static rendering にするためには、動的な関数が存在せず、キャッシュされている必要がある
https://nextjs.org/docs/app/building-your-application/rendering/server-components#dynamic-functions
dynamic functions とは?
cookie とか searchParams とか

動的か、静的か、これを考える必要はあまりない
代わりに、いつキャッシュし、いつrevalidateするのか、
そしてsteream partを分けることを考える必要がある

streaming は、loading.tsx または Suspenceとともに使われる概念

次回 client componentから
https://nextjs.org/docs/app/building-your-application/rendering/client-components

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders
スクロール時の背景画像の固定

{
background-attachment: scroll その領域に対して固定
background-attachment: fixed ウィンドウに対して固定
background-attachment: local その領域の特定の場所に固定
}

https://mdn.github.io/learning-area/css/styling-boxes/backgrounds/background-attachment.html
わかりやすい挙動のちがい

次回 テキスト方向の操作
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Handling_different_text_directions

miroscularmiroscular

4/11

type-challenge/leetcode

https://leetcode.com/problems/restaurant-growth/solutions/4974101/izzi-medium-top-2024-sql50-39/
window関数、サブクエリなどを組み合わせる難問

sum(amount) over(
  order by
    visited_on range between interval 6 day preceding
    and current row
) amount

上は下記と同じ

sum(amount) over(
  order by
    visited_on range interval 6 day preceding
) amount

上から7番目のoffsetととろうとしたとき、

where
  visited_on >= (
    select
      visited_on
    from
      Customer
    order by
      visited_on
    limit
      1
  ) + 6

下記の書き方でも行ける

WHERE visited_on >= (
        SELECT DATE_ADD(MIN(visited_on), INTERVAL 6 DAY)
        FROM customer
    )

https://github.com/type-challenges/type-challenges/blob/main/questions/00018-easy-tuple-length/README.ja.md
length of tuple
lengthをプロパティとして持つtypeをgenericsとして指定しなければならない

個人開発

https://typescriptbook.jp/reference/type-reuse/utility-types/record
Record 型
組み込みユーティリティ型

Terraform / AWS

  ssl_support_method = "sni-only"

これの設定値の意味について
sniとは?
server name indication

https://www.stream.co.jp/blog/blogpost-38236/
要するに、一つのグローバルIPで複数の独自ドメイン、証明書を使ってアクセスが出来る仕組み?

Frontend Mentor

header, footer, main, nav, article, aside, section について
https://web-manabu.com/html-css48/#google_vignette

Next.js

server rendering の利点
キャッシュ可能、リクエスト間での使い回しも可能
パワーの足りない端末でも快適に利用可能
データベースに近いところで取得ができたりする
セキュア
SEO対策, social card
streaming

server components のレンダリングの2step

サーバー側
RSCpayload形式でレンダリング
client component のjavascript instructions を使ってHTMLをサーバーでレンダリングする

クライアント側
最初のロードで既にレンダリングされたHTMLが表示される
RSCとかがなんやかんや調整される
javascript instructions をhydrateしてinteractiveな画面を作る

次回、static rendering より
https://nextjs.org/docs/app/building-your-application/rendering/server-components#server-rendering-strategies

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders

.box {
  background-position: top 20px;
  background-position: top 10%;
  background-position: top center;
  background-position: 水平方向 垂直方向
  background-position: top 20px right 10px
}

backgroundイメージが複数指定されている場合は、対応する位置にある指示に従う

.box {
  background-image: url(star.png), url(big-star.png);
  background-repeat: no-repeat, repeat-x
}

https://cssgradient.io/
css gradient でグラデーションを生成できる

次回以下から
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders#スクロール時の背景画像の固定

4/10

AOJ

https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_7_A
nodeが不定数の子を持つデータ構造

https://github.com/sniper-fly/AOJ/commit/9192726f7ae17a1c047510f759200d0ac8c02b9e
螺旋本解説の余計で保守性の低い無駄な配列を削除して一つに統合
テストも通る

個人開発

next.js のソースコード書き換え
https://github.com/vercel/next.js/issues/53127

色んなパターンのlaunch.jsonを工夫するも、unbound breakpoint になってしまい、
これを解消する方法が見つからず2h掛けたもののデバッグは不可能と判断

pages router でdebugができるかどうか

Terraform / AWS

https://dev.classmethod.jp/articles/terraform-aws-certificate-validation/
こちらの方法が一番正しかった

for_each, for の使い方について
https://qiita.com/hikaru_motomiya/items/fdd784adb5134c31120c
for はlistからmapを作りたい時に使う
for_each はmap からresource大量作成する時に使う

terraform で ACMを作成する際にバージニア北部で作成したい
https://qiita.com/tos-miyake/items/f0e5f28f2a69e4d39422

providerをus-east-1 で作ってaliasを作る

参考
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/acm_certificate
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/route53_record

Frontend Mentor

https://developer.mozilla.org/ja/docs/Web/CSS/CSS_flexible_box_layout/Aligning_items_in_a_flex_container#配置と_flex-direction

items-center
align-items: center
の意味について

主軸と交差軸が存在しalign-itemsは交差軸に対して要素を中央に揃える
flexでは交差軸は縦になる
flex-col では交差軸は横方向になるため、要素を中央揃え出来る

Next.js

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Operators/void
void演算子の使い方がよくわからない

https://nextjs.org/docs/app/building-your-application/data-fetching/patterns#preloading-data
preload テクニック

import { getItem } from '@/utils/get-item'
 
// preload 関数を定義しておいて、下記のItemで呼び出す getItemを呼べるようにしておく
export const preload = (id: string) => {
  // void evaluates the given expression and returns undefined
  // https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/void
  void getItem(id)
}
export default async function Item({ id }: { id: string }) {
  const result = await getItem(id)
  // ...
}
import Item, { preload, checkIsAvailable } from '@/components/Item'
 
export default async function Page({
  params: { id },
}: {
  params: { id: string }
}) {
  // starting loading item data
  // Item コンポーネントを下で使うので、予め読み込み用の関数を呼び出しておく
  preload(id)
  // perform another asynchronous task
  const isAvailable = await checkIsAvailable()
 
  return isAvailable ? <Item id={id} /> : null
}

https://react.dev/reference/react/experimental_taintObjectReference
taint
共同開発で使えそう
client コンポーネントに値をワタシたくない場合、明示的に指定する

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Box_Model_Tasks#課題_3
box model skill テスト

background-repeat プロパティで画像の繰り返し方向を指定したり出来る
no-repeatで一つにすることも

次回以下から
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Backgrounds_and_borders#:~:text=みましょう。-,背景画像のサイズ指定,-先ほどの例
background-size プロパティによって contain, coverなど色々指定可能

4/9

AOJ type-challenge

type First<T extends any[]> = T extends [] ? never : T[0]

extends で、型の条件分岐が可能

一番わかりやすい記事
https://zenn.dev/nbr41to/articles/7d2e7c4e31c54c

generic constraints の具体的な使い方まで載ってる
https://dev.to/tomoy/three-ways-of-using-extends-in-typescript-3dld

never を網羅性チェックに使う
https://typescriptbook.jp/reference/statements/never

ラムダ式でのキャプチャ機能
https://cpprefjp.github.io/lang/cpp11/lambda_expressions.html
これを使うことで、クロージャみたいな動作を実現できる

lambda の[]内でどの変数をキャプチャするか決められる
std::function を使って簡単にラムダの型を宣言できる

void rec(int u, int p, vector<int>& d, const vector<Node>& tree) {
  function<void(int, int)> f = [&](int u, int p) {
    d[u] = p;
    if (tree[u].right != NIL) f(tree[u].right, p);
    if (tree[u].left != NIL) f(tree[u].left, p + 1);
  };
  f(u, p);
}

個人開発

aws のbatchGetCommandを利用して複数の検索結果を取得
検索queryの中にも重複があるとエラーになる

node の --inspect オプションについて
https://nodejs.org/en/learn/getting-started/debugging

Next.jsにPRが提案されていて2ヶ月が経っている。
https://github.com/vercel/next.js/pull/60919

workaround な解決策が以下
https://github.com/vercel/next.js/issues/53127

Terraform / AWS

https://help.onamae.com/answer/7883
https://hp-shizuoka.jp/column/2016/10/7515/
DNSの各レコードの意味

Aレコード
address
ドメインをIPアドレスに置き換えるレコード

CNAMEレコード
canonical name
canonical = 正当な

ドメインを別のドメインに転送したいときにつかう
www.hoge.jp ==> hoge.jp

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket_website_configuration#website_domain
s3をAレコードのエイリアスに登録するには、nameのargumentに対して
aws_s3_bucket ではなく、 aws_s3_bucket_website_configuration のリソースのattributeを使う

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/s3_bucket#hosted_zone_id
zone_id は aws_s3_bucket のhosted_zone_idでおk

terraform でdomain validationをする方法
https://dev.classmethod.jp/articles/terraform-aws-certificate-validation/

Frontend Mentor

https://www.frontendmentor.io/challenges/blog-preview-card-ckPaj01IcS/hub
先人を参考に

Next.js

https://nextjs.org/docs/app/building-your-application/data-fetching/patterns#preloading-data
preload 例が少なすぎて何をしているのか全くわからない

次回 以下から
https://nextjs.org/docs/app/building-your-application/rendering/server-components

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Box_Model_Tasks
task1やっていて早速困った

参考に見たが、ベタ書きの値を入れているだけで本当に良いのか?
https://github.com/jdegand/mdn-test-your-skills

その他

fqdn ホスト とは
https://www.nic.ad.jp/ja/basics/terms/fqdn.html
fully qualified domain name

https://www.securify.jp/blog/path-traversal/
path traversal
外部入力の結果をパスとして解釈して処理する
../../../../../ect/passwd などを解釈させてパスワードを盗み取る

https://www.tagindex.com/html_tag/basic/character.html
html 実体参照

4/8

その他

https://www.freelancer.com/
世界中のフリーランス案件を探す

https://careerfoundry.com/en/blog/web-development/freelance-web-developer/
how to become a freelance developper

4/7

type-challenge/leetcode

https://github.com/type-challenges/type-challenges/blob/main/questions/00007-easy-readonly/README.ja.md
MyReadonlyの実装

https://typescript-jp.gitbook.io/deep-dive/type-system/readonly
readonly でのマークについて
constは変数について、readonly はinterface, typeのプロパティに対して使う
as const をオブジェクトの最後につけると全てのプロパティをreadonlyにできる

https://github.com/type-challenges/type-challenges/blob/main/questions/00011-easy-tuple-to-object/README.ja.md

型定義の際、T[number] のような使い方ができる
https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html

const MyArray = [
  { name: "Alice", age: 15 },
  { name: "Bob", age: 23 },
  { name: "Eve", age: 38 },
];
 
type Person = typeof MyArray[number];
       
type Person = {
    name: string;
    age: number;
}

ビルトインの PropertyKey なるものが存在する
https://www.totaltypescript.com/concepts/propertykey-type

// string | number | symbol
type Example = PropertyKey;

個人開発

たった10件の曲について、jsonを作成するだけでなんと500kb
20000曲のjsonサイズは 500 * 20,000 = 10,000,000
10GBになるので、ざっくり想定費用は1000円

pricing calculator
https://calculator.aws/#/estimate?id=1ab703e3fdf78d1dab08635b723d0667dc3ac114

https://docs.aws.amazon.com/ja_jp/AmazonS3/latest/userguide/selecting-content-from-objects.html
s3 selectでs3をキャッシュサーバーとして使う
この方法だとデータベースのアイテムの変更とかが難しそうなので、例えばクエリされた回数を記録したり、とかが難しくなる
キャッシュをずっと固定で使う、クエリ回数はDynamoDBで保管する、などやり方を工夫すれば節約できるかも
とりあえずDynamoDBでアニメ100件のデータを入力してみて、料金がどれくらいかかるか

Terraform / AWS

route 53でのドメイン取得
anitunes.click で作成

Aレコードを作成し、エイリアスをs3バケットに指定する

https://docs.aws.amazon.com/ja_jp/acm/latest/userguide/acm-regions.html
cloudfrontでACM証明書を使用するには、バージニア北部の証明書でないと駄目らしい!

Aレコード、CNAMEレコードを作成する
証明書の作成

Frontend Mentor

READMEの整備と提出
その他Tailwindcssで作られたプロジェクトの検索

Next.js

server component でこのようにheadersでHostを削除したりすると、 bad requestになる
やはり自動でヘッダーの値の正当性をチェックしている模様

  headers().delete('Host')

data fetch系は出来る限りサーバー側で行うべき
クライアントのUX体験の向上
センシティブなデータが晒されないように

await でブロックされているコンポーネントがある場合、Suspenc かloading.js
がない限りレンダリングがブロックされる。

次回 preloading から
https://nextjs.org/docs/app/building-your-application/data-fetching/patterns#preloading-data

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/The_box_model
ボックスモデルについて

次回 以下から
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Box_Model_Tasks

その他

メールとセキュリティ

MTA
MUA

SMTP MUAからMTAへのメール転送 or MTA間
POP3 MTAからMUAへのメール転送

メールの過半数は迷惑メール

dv証明書
domain validation
OV証明書、EV証明書

4/6

AOJ

木の学習
次数
深さ
高さ
節点node
辺edge

兄弟
葉または外部節点
内部節点

順序木
二分木

個人開発

import { writeFile } from "fs/promises";

...

const jsonData = JSON.stringify(themes.slice(0, 15));
await writeFile("public/themes.json", jsonData, "utf-8")

publicディレクトリにjsonをアウトプットできる

Object.values, Object.entries を使うことでobjectを配列に変換

Terraform / AWS

ordered_cache_behavior
特定のpath pattern, method でのキャッシュの動作を指定できる
コンソールのどこで設定できるかは謎

amazon certificate manager
証明書のプロビジョニング

resource "aws_cloudfront_distribution" "s3_distribution" {
  origin {
    domain_name = aws_s3_bucket.anitunes_click.bucket_regional_domain_name
    origin_id   = local.s3_origin_id
  }

  enabled             = true
  # is_ipv6_enabled     = true
  # default_root_object = "index.html"

  # logging_config {
  #   include_cookies = false
  #   bucket          = "mylogs.s3.amazonaws.com"
  #   prefix          = "myprefix"
  # }

  # aliases = ["mysite.example.com", "yoursite.example.com"]

  default_cache_behavior {
    allowed_methods  = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = local.s3_origin_id

    cache_policy_id = data.aws_cloudfront_cache_policy.caching_optimized.id

    viewer_protocol_policy = "allow-all"
  }

  # price_class = "PriceClass_200"

  restrictions {
    geo_restriction {
      restriction_type = "whitelist"
      locations        = ["JP"]
    }
  }

  viewer_certificate {
    cloudfront_default_certificate = true
  }
}

originでs3のバケット、ドメインネームなどを指定
default_cache_behavior でキャッシュするメソッドの設定
restrictions でキャッシュが利用できる国の設定が出来る

  restrictions {
    geo_restriction {
      restriction_type = "blacklist"
      locations        = []
    }
  }

このようにして全部の国を許可できると考えたが設定できなかった
default_root_object はoptionalだが、これを設定しないとAccess Deniedになる

今回はs3で一つのサイトしか公開していないが、複数のrouteがあるときもキャッシュは使えるのか?
また、これはcloudfront経由でアクセスしないといけないので、S3に直接アクセスした場合は使えない
URLが変わるのでこれをcloudfront強制にしたい
S3のprincipalもcloudfrontのみで良さそう
https://dev.classmethod.jp/articles/static-web-with-cf-s3-tf/

Frontend Mentor

https://www.to-r.net/media/tailwind-css-arbitrary-variants/
任意の疑似クラスみたいなものも使える

https://zenn.dev/ixkaito/articles/advanced-tailwindcss#css-カスタムプロパティの宣言
カスタムプロパティの宣言

https://stackoverflow.com/questions/77360585/how-to-use-hsl-custom-color-in-tailwind-in-react
hsl値をarbitrary valueとして使える

text-[color:hsl(0,90%,90%)]
のような具合

Next.js

fontの導入
https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts#layouts
layoutの作成

上記のfont指定をNext.jsで形にしてみる

import { ReactNode } from "react"
import { Josefin_Sans } from "next/font/google"

const josefin_sans = Josefin_Sans({
  weight: ['300', '400', '600'],
  subsets: ['latin'],
})

export default function Layout({ children }: { children: ReactNode }) {
  return (
    <div className={`${josefin_sans.className}`}>
      {children}
    </div>
  )
}

Layoutを使って、全体に確実に適用できるようにしたい場合
pageからfontの情報を排除できていい感じ

https://zenn.dev/hayato94087/articles/f6557abbd6d079

フォントの使い方について、応用例まで含めて詳しく
https://zenn.dev/tsuyoshi/articles/894592ac677148

import { Raleway } from "@next/font/google";

const raleway = Raleway({
  variable: "--display-font",
});

MDN CSS

.container > *:first-child {
  font-size: 150%;
}
.container > *:first-child::first-line {
  color: red;
}

子要素である全ての任意のセレクタ(*)を対象にし、直接の子要素に限定(>)、
その中でも最初の子要素にのみセレクタが適用されるようになる

https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Selectors_Tasks#task_4
task 3, 4

次回 task5と以下から
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/The_box_model

その他

4/5

type-challenge/leetcode

https://leetcode.com/problems/monthly-transactions-i/description/
leetcode
sum(if(...)) で大体解ける

extendsについて
https://zenn.dev/nbr41to/articles/7d2e7c4e31c54c

型を渡す側に対して制約を掛ける

interface T {
  name: string
  age: number
}
type hoge = keyof T
// hoge = "name" | "age"

type name = 'firstname' | 'lastname'
type TName = {
  [key in name]: string
}
// TName = { firstname: string, lastname: string }

個人開発

external data sourceを使って、外部コマンドの実行結果をterraformで利用できる
https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/external
https://gist.github.com/tkuchiki/f0b804f2bae96e8676e5d86c0ee2bcb8

https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
.env の他に .env.local, .env.developmentが使える模様

https://qiita.com/ryomoucmei/items/71377b05bb9b3c87cdeb
terraform destroy -target を使うと一部のリソース削除ができるが、推奨されていない

Terraform / AWS

cloudfront
キャッシュサーバーのサービス。エッジで展開する
キャッシュの有効期限はアプリケーションサイドで決める?

route53
マネージドDNSサービス。フェイルオーバールーティングポリシー
(ヘルスチェックがNGになったらS3の別のサイトを表示する)もある。

acm
証明書の提供。Cloudfrontやapi gateway を使う場合は無料で使えるらしい。

https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudfront_distribution
cloudfront distributionの設定

https://qiita.com/Ogin0pan/items/199986966e541d9e9ba4#:~:text=CNAME(Canonical Name)レコードは,ために使われます。
もうちょいちゃんと勉強したほうが良さそうだが、
大体はドメインネームのエイリアスというようなことがなんとなくわかった

AWS-managed なポリシーをhuman readableな文で引用する方法
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/cloudfront_cache_policy

次回
引き続きcloudfrontをterraformで設定していく

Frontend Mentor

https://qiita.com/atomyah/items/e66606056ad45c89ba97
compileエラー
(Error: ' can be escaped with ', ‘, ', ’. react/no-unescaped-entities)
'シングルクォートが入った文字列を``で囲む

https://developer.mozilla.org/ja/docs/Web/CSS/Using_CSS_custom_properties
css 変数
:root で書くことで使える模様

https://tailwindcss.com/docs/using-with-preprocessors
tailwind でcss var を使う

次回 色味やグラデーションをREADMEの指定に合わせる
READMEを整備する

`` で囲む以外のやり方を試す
https://stackoverflow.com/questions/43177074/how-can-i-fix-this-violation-of-this-react-no-unescaped-entitie-of-an-eslint-r

frontend mentorでsubmitする

Next.js

https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#security

https://stackoverflow.com/questions/23940321/what-does-a-closed-over-variable-mean
closed-over variable とは?
おそらく、関数の中で関数定義したときに、caller つまり呼び出し元からはアクセスできない変数のこと

A new private key is generated for each action every time a Next.js application is built. This means actions can only be invoked for a specific build.
これの意味がわからない。
サーバーアクションは特定のビルド時しか呼べない?

Next.jsは関数の内部を暗号化するようで、そのビルドの際に毎回違うprivate keyが作成され、それがサーバー側で復号に用いられている?
だから複数の環境でNext.jsを相補的に動かすような場合、復号キーが違って不都合が生じる場合がある
それを防ぐために、
process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY
これで環境変数を上書きし、復号キーを統一することが出来る模様

next.js はPOSTリクエストでしかserver action を invokeできない
また、host と origin ヘッダーの一致を確かめるため、これらが違うとリクエストは中止される

次回ここから
https://nextjs.org/docs/app/building-your-application/data-fetching/patterns
next.jsのリクエストヘッダーについて実際にブラウザで確認
use serverを使っているpageでheaderを書き換えたら動かなくなるのか検証

MDN CSS

https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Selectors_Tasks

task 1の回答

h1 {
  color: blue;
}
h2 {
  color: white;
  background: blue;
}
span {
  font-size: 200%
}

task2 の回答

#special { background: yellow; }
.alert { border: 1px solid grey; }
.alert.stop { background: red; }
.alert.go { background: green; }

task3 意外とわからん

nth-childを使う模様
https://developer.mozilla.org/ja/docs/Web/CSS/:nth-child

 a[href]:visited { color: green }
a[href] { color: orange }
a[href]:hover { text-decoration: none }
.container::first-line { color: red }
.container > p:first-child { font-size: 150% }

ここに回答例が載っているので困ったら見る
https://github.com/jdegand/mdn-test-your-skills

次回 task3 から task5 まで

miroscularmiroscular

4/4

AOJ

https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_6_D

int solve(int len, const vector<int>& nums, int min_all) {
  int          ans = 0;
  vector<int>  dest(nums.begin(), nums.end());
  vector<int>  T(len + 1, -1);
  vector<bool> V(len, false);

  // まず、ソート後の目標とする配列を用意する
  sort(dest.begin(), dest.begin() + len);

  rep(i, len) { T[dest[i]] = i; }
  rep(i, len) {
    if (V[i]) continue;
    int cur          = i;
    int sum          = 0;
    int min_in_cycle = VMAX;
    int cycle_len    = 0;
    while (true) {
      V[cur] = true;
      ++cycle_len;
      const int v  = nums[cur];
      min_in_cycle = min(min_in_cycle, v);
      sum += v;
      cur = T[v];
      if (V[cur]) break;
    }
    // サイクル内の要素での最小コスト vs サイクル外の最小値を借りた場合のコスト
    ans += min(sum + (cycle_len - 2) * min_in_cycle,
        sum + min_in_cycle + (cycle_len + 1) * min_all);
  }

  return ans;
}

何を表しているかわからなかったV, Tの意味がようやくわかった
計数ソートの考えが一部で取り入れられていて、
Tは、要素として、与えられた数字列の各数字がソート後の配列で配置されるべきインデックスを示している。
要するに idx が 各数字、その要素の数字が配置されるべきインデックスになっている。
vはサイクル内の数字を表していて、curはその数字がソート後に配置されるべきインデックスを示している
keyを各数字とし、要素を配置されるべきインデックスとして収納されている辞書であればわかりやすかった。
計数ソートもそうだが、実際は辞書やmapの方が無駄なインデックスがなくて済むのでは?
Vの要素はそのインデックスの要素(numsに対応する)が探索済みかどうか、を示す
サイクルの長さが1つの場合はV[cur]がtrueになるので、次のサイクルに移ることとなる
サイクルの長さが2以上の場合は、サイクルの最後でサイクルの最初の要素に戻ってくることになるので、v[cur]がtrueとなりループ終了

https://github.com/sniper-fly/AOJ/blob/master/ALDS1_6_D/main.cpp
書籍に掲載されている変数名がゴミなので、より人間が読める形での変数名に変換した

個人開発

https://dev.classmethod.jp/articles/aws-iam-with-path/
iam に存在するパスについて
あとからフィルタリングできる程度

https://dev.classmethod.jp/articles/iam-role-and-assumerole/
assume roleとは何なのか?

https://qiita.com/reflet/items/dc109d1856b1ea525284
keybaseを使わず、自前でgpg鍵を用意してパスワードを複合したりする

https://nao-eng.com/posts/2022/11/about-terraform-iam/
keybaseというサービスを使ってaccess_keyを取得する方法
outputされたアクセスキーをどうやって複合するかという肝心の手順がない

keybaseの紹介 記事古い
https://qiita.com/yyu/items/b444d7a51c30ee071588

keybaseやら鍵を使わず、stateファイルに平文でキーが保存される例
https://www.pulumi.com/ai/answers/fQ3mkrMM81Jf3Hk5DkQdsZ/creating-aws-iam-access-keys-with-terraform

iamポリシーの付与は以下のページに詳細が載っている
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_user_policy
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_user_policy_attachment
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document

keybaseコマンドでdecryptする例が載っている
https://book.keybase.io/docs/cli#decrypting-a-pgp-message

https://book.keybase.io/docs/linux#autostart
keybaseのインストール方法

https://lecture.ecc.u-tokyo.ac.jp/JOHZU/joho/Y2023/GPG/GPG/gpg_1.html
gpg鍵について

Terraform / AWS

AWSのポリシーでよく見る principal とは?
https://docs.aws.amazon.com/ja_jp/AmazonS3/latest/userguide/s3-bucket-user-policy-specifying-principal-intro.html

誰にリソースのアクセスを許可するか、という話
awsのユーザーARNを使うこともできる

SID とは?
https://docs.aws.amazon.com/ja_jp/IAM/latest/UserGuide/reference_policies_elements_sid.html
Statement配列内のid。一意に指定されなければならない。
説明的なid名をつければよさそう。

https://qiita.com/curlneko/items/c245c40162fafa1fee71
s3オブジェクトのcontent-typeをterraformで指定しない場合
メタデータが
application/octet-stream
になってしまう
とはいえ、for_eachを使っている都合上、content-typeは各々違って当然なので、指定が難しい
https://stackoverflow.com/questions/76170291/how-do-i-specify-multiple-content-types-to-my-s3-object-using-terraform
この問題に対する回答
Terraformで使える関数を把握する

アクセスするURLが間違っていた模様
objectの方からURLを取得すると上手く行かない

以下のコードでとりあえず今あるファイルの種類に応じたcontent-typeの設定が可能

locals {
  content_types = {
    "js"   = "application/javascript"
    "html" = "text/html"
    "css"  = "text/css"
    "png"  = "image/png"
    "ico"  = "image/x-icon"
  }
}

resource "aws_s3_object" "resources" {
  bucket = aws_s3_bucket.anitunes_click.id

  for_each = fileset("./resources/", "**")

  key    = each.value
  source = "resources/${each.value}"

  content_type = lookup(local.content_types, reverse(split(".", each.value))[0], "text/plain")

  etag = filemd5("resources/${each.value}")
}

Frontend Mentor

https://tailwindcss.com/docs/content-configuration#dynamic-class-names
動的にTailwindのクラス名を生成することは禁止されている
常にcompleteなclass name を使わないとエラーになる
その関係上、 arbitrary value で対応するには bg-[url(/base-apparel-coming-soon-master/bg-pattern-desktop.svg)]
これをベタ書きせねらばならず、実用的でない。
総合的に見れば、変数によって文字列の再利用が可能な以下がよさそう

<div
  className="md:hidden bg-cover w-full h-80 mb-10"
  style={{
    backgroundImage: `url(${basePath}/hero-mobile.jpg)`,
  }}
></div>

tailwindのクラス名並べ替えを自動で
https://github.com/tqwewe/prettier-plugin-tailwind
上のpluginは古いため動かなかった

下の最新の、公式のプラグインを使うことで動いた
https://github.com/tailwindlabs/prettier-plugin-tailwindcss

Next.js

https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#optimistic-updates
useOptimistic

Next.jsの公式ドキュメントでは何を言っているかわからない
Reactの公式
https://ja.react.dev/reference/react/useOptimistic

multiple form actionについて
https://ja.react.dev/reference/react-dom/components/form#handling-multiple-submission-types

requestSubmit
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit
これをつかうことでformのsubmitができ、サーバーアクションをinvokeできる
最も近い祖先のformをtriggerする

サーバーアクションが完了するまでに暫定的なUIを表示したい
useOptimistic や useTransition を使いたい
https://ja.react.dev/reference/react/useTransition

次回セキュリティから
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#security

開発者は、server actionがpublicに公開されているAPIを扱うかのごとく開発しなければならない
認証忘れずに

MDN CSS

次回以下より
https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Selectors_Tasks
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/The_box_model

その他

4/3

leetcode

https://leetcode.com/problems/monthly-transactions-i/description/

個人開発

ローカルで動くプログラムへの認証方法
まずiamユーザーをコンソールログイン機能なしで作成し、
セキュリティ認証情報からアクセスキーを作成

下記の認証方法を頼りに、.envに環境変数を設定する
https://docs.aws.amazon.com/ja_jp/sdk-for-java/v1/developer-guide/setup-credentials.html
AWS_ACCESS_KEY_ID、AWS_SECRET_ACCESS_KEY の設定だけでおk

まだエラーが出たので下記を見るがユーザーに割り当てられたポリシー的には全く問題なさそう
https://docs.aws.amazon.com/ja_jp/amazondynamodb/latest/developerguide/using-identity-based-policies.html

アプリ再起動で治った。

iamロールの作成もTerraformで行い、アクセスキーをoutputでローカルにのみ保存するようにすれば
destroyでまとめて削除できそうなので、次回やってみたい
.env以外の .aws.env みたいなファイルを自動で作って更新できるようにできないか?

とりあえず認証が通ってクエリを通すところまでは達成

assume a role が代替として使えるかと思ったが、よくわからないのでスキップ
https://docs.aws.amazon.com/sdkref/latest/guide/access-assume-role.html

Terraform / AWS

https://developer.mozilla.org/ja/docs/Web/HTTP/Basics_of_HTTP/MIME_types
MIME type とは?
text/html image/png audio/mpeg など

etagを設定しないと、index.html をupdateしても検知してくれない

ファイルを上げる際にオブジェクトごとにいちいちresourceを書くのがめんどくさい↓
https://qiita.com/curlneko/items/b9c70d6d6da2559531c9

for_each を使ってまとめて作成できそう

次回ディレクトリごとアップロード

Frontend Mentor, Next.js

redirect関数はreturnのように関数の戻り値に影響を与える模様
どのように関数の戻り値を推論して決定するのか?が謎

zod, useFormStateを利用してサーバーサイドのバリデーションを実装
https://github.com/sniper-fly/frontend_mentor/blob/master/src/app/base-apparel-coming-soon-master/page.tsx
https://github.com/sniper-fly/frontend_mentor/blob/master/src/app/base-apparel-coming-soon-master/registerEmail.ts
https://github.com/sniper-fly/frontend_mentor/commit/b8d5b8b22b9f9a8a458c479215f335b904ecaee6

次回 frontend mentor
bgイメージをarbitary valuesで対応

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements#擬似クラスと擬似要素を組み合わせる

疑似クラスで、特定の状態にあるときにクラスを追加したかのように振る舞う
疑似要素で、あたかもDOMに要素を追加したかのように動作する

::before で特定のセレクタの前に何か content を使って要素の追加が可能

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Selectors/Combinators
子孫結合子
.box p
.box クラスを持つ要素の子孫全てに適用される

子結合子
.box > p
.box クラスを持つ要素の子にのみ適用される

次回、次兄弟結合子から
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Selectors/Combinators#次兄弟結合子

その他

以下のようにシェルスクリプトでディレクトリごとに走査したい場合に使える

  for dir in */; do

ECSからサーバーレスに移行した記事
https://zenn.dev/seapolis/articles/6d761e37317b58#利点-%2F-弱点-%2F-今後の展望

4/2

AOJ

https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_6_D

0 1 2 3 4 5 6 7 8 9 10 (idx)
1 2 7 8 9 10 (nums)
0 0 1 0 0 0 0 2 3 4 5
V
0 0 0 0 0 0
1 0 0 0 0 0

サイクルを求める計算のやり方イマイチわからない。。。
なぜそうなる?のか

個人開発

dynamodbテーブルをterraformで作成
docker環境にしたせいで、AWS CLIが使えない
docker内からでも安全にAWSを操作したい

Terraform / AWS

aws_s3_bucket_public_access_block
でデフォルトでpublic access blockを解除できる

これでpublic access blockを解除して即公開可能ではなく、bucket policyを定義して初めて公開できる

static_website_hosting のような設定項目はなく、
以下のリソースを定義するだけでstaticウェブサイトの定義が可能
aws_s3_bucket_website_configuration

バケットポリシーの作成

次回
ファイルのアップロード
https://qiita.com/curlneko/items/5ce323b0cd509dd5416f
こちら参考にできそう

Frontend Mentor

https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#forms
useFormStateを参考に、stateを使わずにformの送信ができる動作の実現を目指しているが下記のエラー

Overload 1 of 2, '(action: (state: { errors: { email?: string[] | undefined; }; } | undefined) => { errors: { email?: string[] | undefined; }; } | Promise<{ errors: { email?: string[] | undefined; }; } | undefined> | undefined, initialState: { ...; } | undefined, permalink?: string | undefined): [state: ...]', gave the following error.
    Argument of type '(prevState: any, formData: FormData) => Promise<{ errors: { email?: string[] | undefined; }; } | undefined>' is not assignable to parameter of type '(state: { errors: { email?: string[] | undefined; }; } | undefined) => { errors: { email?: string[] | undefined; }; } | Promise<{ errors: { email?: string[] | undefined; }; } | undefined> | undefined'.
      Target signature provides too few arguments. Expected 2 or more, but got 1.
  Overload 2 of 2, '(action: (state: { errors: { email?: string[] | undefined; }; } | undefined, payload: FormData) => { errors: { email?: string[] | undefined; }; } | Promise<{ errors: { email?: string[] | undefined; }; } | undefined> | undefined, initialState: { ...; } | undefined, permalink?: string | undefined): [state: ...]', gave the following error.
    Object literal may only specify known properties, and 'message' does not exist in type '{ errors: { email?: string[] | undefined; }; }'

長すぎて読めない。

これが

    (prevState: any, formData: FormData) => Promise<
      { errors: { email?: string[] | undefined; }; } | undefined
    >

これにnot assignable ということらしい

    (state: { errors: { email?: string[] | undefined; }; } | undefined) => {
      errors: { email?: string[] | undefined; };
    } | Promise<
      { errors: { email?: string[] | undefined; }; } | undefined
    > | undefined

learn next.js を見直して再実装する必要がありそう

Next.js

FrontEnd mentor の続き

input, select タグのなかに name="hoge" のような属性を埋め込むと、
formDataから取得が可能になる

MDN CSS

https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Selectors/Attribute_selectors
属性セレクター

属性の値によってセレクタを適用するか決められる

a[href^="hoge"]
のように正規表現っぽい指定方法もある

a {
  border: 5px solid grey;
}

a[title] {
  border-color: pink
}

a[href*="contact"] {
  border-color: orange
}

a[href^="https"] {
  border-color: green
}
<ul>
  <li><a href="https://example.com">Link 1</a></li>
  <li><a href="http://example.com" title="Visit example.com">Link 2</a></li>
  <li><a href="/contact">Link 3</a></li>
  <li><a href="../contact/index.html">Link 4</a></li>
</ul>

次回、疑似クラス、疑似要素の組み合わせから
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Selectors/Pseudo-classes_and_pseudo-elements

動的疑似クラス→ホバーした時に適用されるCSSの決定など
first-line、first-child などで最初の要素のみを指定したり、
最初の行がまるでspanでラップされているかのように振る舞う

4/1

AOJ

https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_6_D
各サイクルそれぞれにおいて、要素全体の最小値を借りた場合と借りない場合での
コストを計算して小さい方を採用する

  // numsは同じ型のvector 下記のような感じでコピーできる
  const vector<int> dest(nums);

  // sort
  sort(dest.begin(), dest.end());

個人開発

spotify APIの検索精度調査
英語での検索だとあまり正確な結果が出てこない場合がある

https://blog.geckour.com/posts/2020/0603-play-with-spotify-api/
spotify api クエリについて

Terraform / AWS

route53でAWSクレジットを利用したドメインの取得ができそう
billing and cost management/クレジット からクレジットが適用可能な製品を確認

ホストゾーン数 というのがよくわからない。
これは固定費として必ずかかるものなのか、従量課金なのか?
無料枠は存在するのか?

お名前ドットコムなどで普通に取得しても良いかも知れない。
クレジットが使えるうちに固定費の支払いをすることで料金請求になれておくべきかも。

Frontend Mentor

https://tailwindcss.com/docs/order
order-2 などの指定をすることで、flexなどを利用したときDOMでの登場順とは違う順番に要素を並べることが出来る

Next.js

useFormStatus と useFormState が存在する
useFormStatus はフォーム送信時のpending状態を取得できる

useFormState を使うことで リデューサのような動作になる
サーバーバリデーション後にクライアントにメッセージを表示できる
actionに、formDataに加えてprevState引数が一個増える

次回以下 optimistic updates から
https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#optimistic-updates

MDN CSS

カンマ区切りによって、複数のセレクタに対してまとめて設定を行える
単なるスペース区切りだと、 h1 div とかだと h1 の直後に来たdiv要素、となる

特定の要素の特定のプロパティ、値を持つセレクタも存在する

a[href="https://example.com"] {
  ...
}

タイプセレクタ
要素名をそのまま書くやつ。

ユニバーサルセレクタ

  • で全選択するやつ。
    ブラウザの動作リセットか、可読性の向上でのみ使うべき。

次回 以下から
https://developer.mozilla.org/ja/docs/Learn/CSS/Building_blocks/Selectors/Attribute_selectors

このスクラップは5ヶ月前にクローズされました